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:
- static void Main(string[] args)
- {
- var Obj_ = new
- {
- Name = "Pankaj",
- City = "Alwar",
- State = "Rajasthan"
- };
- WriteLine($ "Name of Employee={Obj_.Name} \n City={Obj_.City} \n State ={Obj_.State}");
- ReadLine();
- }
Output:
Name of Employee=Pankaj
City=Alwar
State =Rajasthan
How Its Works:
- For anonymous type syntax, the compiler generates a class.
- Properties of the class generated by the complier are value and data type given in the declaration.
- 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.
- static void Main(string[] args)
- {
- var Obj_ = new []
- {
- new
- {
- Name = "Pankaj",
- City = "Alwar",
- State = "Rajasthan"
- },
- new
- {
- Name = "Rahul",
- City = "Jaipur",
- State = "Rajasthan"
- }
- };
- WriteLine($ "Name of Employee={Obj_[1].Name} \n City={Obj_[1].City} \n State ={Obj_[1].State}");
- ReadLine();
- }
Output:
Name of Employee=Rahul
City=Jaipur
State =Rajasthan