Anonymous Types and LINQ
Anonymous types, introduced in C# provides the facility to encapsulate a set of properties into a type without specifically naming the type in source code as shown below:
var prod = new { Name="xyz",Price=12.00};
In this case compiler internally generates code for a type in the IL code.If you check the IL code you'll find a type with name
<>f__AnonymousType0`2'<'<Name>j__TPar','<Price>j__TPar'>
Anonymous types
- Has to be instantiated with new keyword during declaration
- Can only contain public read-only properties
- Are reference types derived from System.Object and Equals returns true if values of all the properties are same.
- If two anonymous types are declared with same properties in same order then compiler generates code for a single type which is shared between the two e.g. For the code shown below a single type <>f__AnonymousType0`2'<'<Name>j__TPar','<Price>j__TPar'> is generated in IL
var prod = new { Name="xyz",Price=12.00};
var prod1 = new { Name = "xyza", Price = 120.00 };
For the code shown below two types '<>f__AnonymousType0`2'<'<Name>j__TPar','<Price>j__TPar'> and
'<>f__AnonymousType1`2'<'<Price>j__TPar','<Name>j__TPar'> is generated in IL code as order of the properties are different
var prod = new { Name="xyz",Price=12.00};
var prod1 = new { Price = 120.00,Name = "xyza" };
Anonymous types are used LINQ to select a subset of properties from the source object in a query as shown below:
Person[] plist = new Person[] {
new Person{FirstName="John",LastName="Doe",City="New York"},
new Person{FirstName="Sankarsan",LastName="Bose",City="Kolkata"}};
var per = from p in plist
select new { p.FirstName, p.City };
In my next post I will be discussing about usage of Generic Types in LINQ.