Thursday, February 4, 2010

Anonymous Types

The ability to create new types 'on the fly' is done using Anonymous Types.

All of this happens at compile time, so anonymous types are still strongly typed. In reality, the compiler automatically creates a class that represents the anonymous type.

Example: var product = new {Name = "C# Rocks!", Price = 3};

-> When an anonymous type is assigned to a variable, that variable must be initialized with the var construct.

-> Anonymous types are reference types that derive directly from object.

-> If two or more anonymous types have the same number and type of properties in the same order, the compiler treats them as the same type and they share the same compiler-generated type information.

-> Anonymous types cannot contain unsafe types as properties.

Note: While anonymous types might not seem all that useful on the surface, they are the cornerstone for LINQ. Without anonymous types, LINQ would not be able to create types dynamically. This is what allows LINQ to query for an arbitrary set of data, without first having the structure declared.