29 August 2012

List of an anonymous type

Anonymous types allows us to easily encapsulate a set of read-only properties of single object without the need to define a type first.
The type name is generated by the compiler and each property type is inferred by the compiler.

Anonymous types are useful when using LINQ for example.

A List of an anonymous type is something that at the first thought seems rather impossible, but for everything there is always a solution:

1) First define the anonymous type:
 var person = new { Id = 1, Name = "John Doe" };
2) Then create the list of the anonymous type
var people = (new[] { person }).ToList();
4) Add more items to the list easly
people.add(new { Id = 2, Name = "Peter Doe" });

No comments: