Author : Rahul
Last Modified : 14-May-2021
Complexity : Beginner

Anonymous Types in C#


Anonymous Type

Anonymous Types are those types that do not contain any name or we can create new type without defining them.

Syntex

var object_name = new
{
Property_1 = Value_1,
Property_2 = Value_2
};

Description

  1. object_name: Object name of Anonymous type
  2. Property_1: First property name of Anonymous type
  3. Value_1: First property value of Anonymous type
  4. Property_2: Second property name of Anonymous type
  5. Value_2: Second property value of Anonymous type

Example

// C# program to define the anonymous type
using System;
  
  public class Test
  {
    static public void Main()
    {
      // Create and initialize anonymous type
      var obj = new
      {
        StudentId = 101,
        StudentName = "Rahul"
      };

      // Access object property
      Console.WriteLine("Student Id: " + obj.StudentId);
      Console.WriteLine("Student Name: " + obj.StudentName);
    }
  }

Output

Student Id: 101
Student Name: Rahul

Properties

Below are some properties of Anonymous Types:

  1. They are introduced in C# 3.0.
  2. They are derived from System. Object class.
  3. They are sealed class. So they are not used as a base class for other classes.
  4. They do not contain events and methods.
  5. They can only be converted into Object type.
  6. They are reference type.
  7. Its properties are read-only so we can not change their values.
  8. They are not used as a return type of the Method or Indexer.
  9. They are not used as a type of other property.
  10. They are not passed as a parameter into Method, Indexer or Constructor.
  11. The scope of these types is local meaning that their scope is limited to the method in which they are defined.

 

Restriction / Limitation

Below are some restriction of Anonymous Types:

  1. They can contain only public fields.
  2. These fields can be initialized at the time of declaration.
  3. They can not contain events and methods.
  4. Anonymous Type and its fields can not static.
  5. They can not implement Interface.

 

Uses / Anonymous type in LINQ

The main use of Anonymous type in querying LINQ query. It is very useful when we are querying object collection (Array or List) using LINQ query and this object contains many properties but we want to return only some properties.
Suppose we have Student Class. This class contains StudentId, StudentName and StudentMarks properties. We have some students with these properties. We want to get all those students with StudentId and StudentName, having marks of more than 50. In this case, Anonymous types are very useful. The below code is used to define uses of Anonymous type in LINQ.

// C# program to define the anonymous type
using System;
using System.Collections.Generic;
using System.Linq;

  public class Student
  {
    public int StudentId { get; set; }
    public string StudentName { get; set; }
    public int StudentMarks { get; set; }
  }

  public class Test
  {
    static public void Main()
    {
      List<Student> lstStudent = new List<Student>();
      lstStudent.Add(new Student { StudentId = 101, StudentName = "Rahul", StudentMarks = 70 });
      lstStudent.Add(new Student { StudentId = 102, StudentName = "Pardeep", StudentMarks = 20 });
      lstStudent.Add(new Student { StudentId = 103, StudentName = "Ankur", StudentMarks = 30 });

      // Create and initialize anonymous type
      var obj = from s in lstStudent
                where s.StudentMarks > 50
                select new
                {
                  s.StudentId,
                  s.StudentName
                };

      // Access object property
      foreach (var item in obj)
      {
        Console.WriteLine("Student Id: " + item.StudentId);
        Console.WriteLine("Student Name: " + item.StudentName);
      }
    }
  }

Output

Student Id: 101
Student Name: Rahul

 

Nested Anonymous Type

Anonymous type can contain another anonymous type as a property. The below code is used to define the Nested Anonymous type.

// C# program to define nested anonymous type
using System;
  
  public class Test
  {
    static public void Main()
    {
      // Create and initialize anonymous type
      var obj = new
      {
        StudentId = 101,
        StudentName = "Rahul",
        StudentAddress = new { Email = "[email protected]" }
      };

      // Access object property
      Console.WriteLine("Student Id: " + obj.StudentId);
      Console.WriteLine("Student Name: " + obj.StudentName);
      Console.WriteLine("Student Email: " + obj.StudentAddress.Email);
    }
  }

Output

Student Id: 101
Student Name: Rahul
Student Email: [email protected]