Anonymous types allows users to create objects without creating classes. In many cases, we may need to store compound related data, but that will be referred in within a particular method. In .net framework 2.0, anonymous types, we have to write a simple classes and properties to achieve this.
Anonymous types works with Automatic Type Inferencing, Auto Implemented properties and Object Initializers
Example
var e = new {
ID = 10,
Name = "John",
Designation = "Software Engineer",
Age = 25
};
C# Compiler implicitly creates a type and uses it.
Notes:
- As the type name is unknown, automatic type inferencing should be used.
- As Automatic type inferencing is the only option to declare anonymous types, it can be used within code blocks only, can not be used as type member
- Anonymous types with same properties with same property types are considered as equal.
Hence
var e = new {
ID = 10,
Name = "John",
Designation = "Software Engineer",
Age = 25
};
and
var f = new {
ID = 11,
Name = "Mike",
Designation = "Software Engineer",
Age = 26
};
are considered as same type.
- Arrays with anonymous type elements can be created as
var e = new[]{ new {
ID = 10,
Name = "John",
Designation = "Software Engineer",
Age = 25
},
new {
ID = 11,
Name = "Mike",
Designation = "Software Engineer",
Age = 26
}};
- It is not possible to refer property values within declaration. Following statement is WRONG.
var e = new {
ID = 10,
FirstName = "John",
LastName ="Carter",
FullName = FirstName + " " + LastName,
Designation = "Software Engineer",
Age = 25
};
No comments:
Post a Comment