Anonymous Types

Summary

Anonymous Types are types automatically inferred and created from object initializers (at compile time).

Anonymous types provide a way to encapsulate a set of read-only properties into a single object without having to first explicitly define a type.

Code Example

class Program { static void Main(string[] args) { var myGroups = new [] { new {Name= "Garden", Members = new [] {"pot.jpg", "spring.jpg", "barbeque.jpg", "flowers.jpg"}}, new {Name = "Friends", Members = new [] {"restaurant.jpg", "dinner.jpg"}} }; } }

The Anonymous Type created by this declaration would have two properties, Name and Members, with Members being an array of strings. The types would have internal names and would be compatible with any other type of the same structure.

Automatic get properties are created for the listed members, so we can access the value of group.Name.