Anonymous Types are inline class definition which is created at compile time, we use the same syntax of Object Initializer to declare a Anonymous Types but with out the class name
var customer = new {Name = "Paolo Accorti", Country = "Italy"};
In my previous post about Local Type Inference we discussed about the var keyword and how it provides us a relaxed way of declaring variable but in the case of Anonymous Types the usage of the var keyword is a must to assign it to a variable. Anonymous Types is a very handy tool when when we handle data using LINQ
var employeeBirthDates = db.Employees
.Select(e => new {e.FirstName, e.LastName, e.BirthDate});
var employeePhoneNumbers = db.Employees
.Select(e => new {e.FirstName, e.LastName, e.HomePhone});
In the above scenario, it would have been difficult for us to declare each type and change them when we change the shape of the query result, Anonymous Types handles this efficiently, a few important things to know about Anonymous Types are as following
Anonymous Types can only have Read Only Properties as their members, no Methods can be associated with them, in the above example assigning a property would be illegal
foreach (var birthDate in employeeBirthDates)
birthDate.BirthDate = DateTime.Now; // Error, cannot assign read only property
The Order and the Name of the Properties determine the type signature of the Anonymous Type, for example
var employee1 = new { FirstName = "Nancy", LastName = "Davolio" };
var employee2 = new { FirstName = "Andrew", LastName = "Fuller" };
var employee3 = new { LastName = "Leverling", FirstName = "Janet" };
Console.WriteLine(employee1.GetType().Name);
Console.WriteLine(employee2.GetType().Name);
Console.WriteLine(employee3.GetType().Name);
Output:
<>f__AnonymousType0`2
<>f__AnonymousType0`2
<>f__AnonymousType1`2
we see that employee1 and employee2 are of the same type but employee3 is of a different type because of the order of the properties