Anonymous Type In C#

An anonymous type is a simple data type created on the fly to store a set of values. Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first. Anonymous types were introduced in C# 3.0. These data types are generated by the compiler rather than explicit class definition.

Example:

  1. static void Main(string[] args)  
  2. {  
  3.     var Obj_ = new  
  4.     {  
  5.         Name = "Pankaj",  
  6.             City = "Alwar",  
  7.             State = "Rajasthan"  
  8.     };  
  9.     WriteLine($ "Name of Employee={Obj_.Name} \n City={Obj_.City} \n State ={Obj_.State}");  
  10.     ReadLine();  
  11. }  

Output:

Name of Employee=Pankaj

City=Alwar

State =Rajasthan

How Its Works:

  1. For anonymous type syntax, the compiler generates a class.
  2. Properties of the class generated by the complier are value and data type given in the declaration.
  3. Intellisense supports anonymous type class properties.

 

We can create an array of anonymously typed elements by combining an implicitly typed local variable and an implicitly typed array.

  1. static void Main(string[] args)  
  2. {  
  3.     var Obj_ = new []  
  4.     {  
  5.         new  
  6.         {  
  7.             Name = "Pankaj",  
  8.                 City = "Alwar",  
  9.                 State = "Rajasthan"  
  10.         },  
  11.         new  
  12.         {  
  13.             Name = "Rahul",  
  14.                 City = "Jaipur",  
  15.                 State = "Rajasthan"  
  16.         }  
  17.     };  
  18.     WriteLine($ "Name of Employee={Obj_[1].Name} \n City={Obj_[1].City} \n State ={Obj_[1].State}");  
  19.     ReadLine();  
  20. }  

Output:

Name of Employee=Rahul

City=Jaipur

State =Rajasthan