Anonymous Type In C#

Definition

Anonymous type, as the name suggests is a type that doesn't have any name.Anonymous types are the new concept in C#3.0 that allow us to create new type without defining them. This is a way to define read only properties into a single object without having to define type explicitly. The type name is generated by the compiler and is not available at the source code level. We can create an object with the new keyword without defining its class.

Example

  1. var Anonymous_Type = new   
  2. {  
  3.     firstName = "Pankaj",  
  4.   
  5.         middleName = "Kumar",  
  6.   
  7.         lastName = "Choudhary",  
  8.   
  9.         age = 21,  
  10.   
  11.         City = "Alwar"  
  12. };  

class

class2

Above Anonymous type contain 5 fields. We can see that we don’t require to maintain the data type for any field on anonymous object. We can see that City is a string type and age is integer type property. So compiler applies the appropriate type to each property based on the value expression.

An anonymous type is a temporary data type that is inferred based on the data that we include in an object initializer. Properties of anonymous types are read-only in nature so cannot change their values. Let us try to change the value of Age.

error

Above error confirm that we can’t change property of any Anonymous type object.

Nested Anonymous Type

  1. var Anonymous_Type = new   
  2. {  
  3.     Name = new  
  4.         {  
  5.             firstName = "Pankaj",  
  6.   
  7.                 middleName = "Kumar",  
  8.   
  9.                 lastName = "Choudhary"  
  10.         },  
  11.   
  12.         age = 21,  
  13.   
  14.         City = "Alwar"  
  15. };  

We can define an anonymous type that contain another anonymous type as a property. In above example we defined an anonymous type that is “Anonymous_Type” and this anonymous type contain a nested anonymous type “Name”.

type

Scope of Anonymous Type

Anonymous types are locally scoped. We can’t use a anonymous typed variable as a parameter for a method. But we can pass anonymous type for a method that accept dynamic type.

Example

  1. class Program  
  2.   
  3. {  
  4.   
  5.     static void Main(string[] args)  
  6.   
  7.     {  
  8.   
  9.         var Anonymous_Type = new {  
  10.             firstName = "Pankaj",  
  11.   
  12.                 middleName = " Kumar",  
  13.   
  14.                 lastName = " Choudhary",  
  15.   
  16.                 age = 21,  
  17.   
  18.                 City = "Alwar"  
  19.         };  
  20.   
  21.         Call(Anonymous_Type);  
  22.   
  23.         Console.ReadKey();  
  24.   
  25.     }  
  26.   
  27.     static void Call(dynamic Data)  
  28.   
  29.     {  
  30.   
  31.         Console.WriteLine("My Name is: " + Data.firstName + Data.middleName + Data.lastName);  
  32.   
  33.         Console.WriteLine("My Age is: " + Data.age);  
  34.   
  35.         Console.WriteLine("I live in: " + Data.City);  
  36.   
  37.     }  
  38.   
  39. }  

Output

output

Why we need of Anonymous Type

Anonymous types have been introduced to support one of the most useful feature called LINQ. It's most useful when we are querying collection of object using LINQ query and we want to return only a few of its properties. Anonymous types contain one or more public read-only properties. No other kinds of class members, such as methods or events, are valid. The expression that is used to initialize a property cannot be null

Example:

  1. public class Employee  
  2.   
  3. {  
  4.   
  5.     public string Name  
  6.     {  
  7.         get;  
  8.         set;  
  9.     }  
  10.   
  11.     public string City  
  12.     {  
  13.         get;  
  14.         set;  
  15.     }  
  16.   
  17.     public int Age  
  18.     {  
  19.         get;  
  20.         set;  
  21.     }  
  22.   
  23.     public string Post  
  24.     {  
  25.         get;  
  26.         set;  
  27.     }  
  28.   
  29. }  
  30.   
  31. class Program  
  32.   
  33. {  
  34.   
  35.     static void Main(string[] args)  
  36.   
  37.     {  
  38.   
  39.         List < Employee > Employee_obj = newList < Employee >  
  40.           {  
  41.   
  42.             newEmployee()  
  43.            {  
  44.                 Name = "Pankaj", City = "Alwar", Age = 21, Post = "Developer"  
  45.             },  
  46.   
  47.             newEmployee()   
  48.           {  
  49.                 Name = "Rahul", City = "Jaipur", Age = 22, Post = "Designer"  
  50.             },  
  51.   
  52.             newEmployee()   
  53.           {  
  54.                 Name = "Sandeep", City = "Delhi", Age = 20, Post = "Developer"  
  55.             },  
  56.   
  57.             newEmployee()   
  58.           {  
  59.                 Name = "Neeraj", City = "Alwar", Age = 23, Post = "Designer"  
  60.             }  
  61.   
  62.         };  
  63.   
  64.         varEmp =  
  65.   
  66.             fromEmp_ inEmployee_obj  
  67.   
  68.         selectnew  
  69.   
  70.         {  
  71.   
  72.             Emp_Name = Emp_.Name,  
  73.   
  74.                 Emp_Age = Emp_.Age  
  75.   
  76.         };  
  77.   
  78.         foreach(varObjinEmp)  
  79.   
  80.         {  
  81.   
  82.             Console.WriteLine("Employee Name is: " + Obj.Emp_Name + "Employee Age is: " + Obj.Emp_Age);  
  83.   
  84.         }  
  85.   
  86.         Console.ReadLine();  
  87.   
  88.     }  
  89.   
  90. }  

Output

output

Point To Consider

  • Anonymous types are class type, directly derived from “System.Object”, so they are reference type.
  • Anonymous type can be defined using the new keyword and object initializer syntax.
  • Anonymous type is a reference type.
  • Properties of the Anonymous type are read only.
  • The compiler provides a name for each anonymous type, although your application cannot access it.
  • Anonymous type has method scope. If we want to return Anonymous type from the method, then you have to convert it in object type or we want to pass Anonymous type as parameter for a function then we should use the Dynamic Type.
  • If two Anonymous types have the same properties and same order, then the compiler treats it as the same type, but both Anonymous must be in same assembly.
  • We cannot declare a field, a property, an event, or the return type of a method as having an anonymous type.
  • The implicitly typed variable “var”, is used to hold an anonymous type.

Up Next
    Ebook Download
    View all
    Learn
    View all