Now that we've introduced the "var" keyword, we
can start to use it to refer to anonymous types.
Anonymous types in C# are defined using the same object initializer syntax I covered in my first blog post in this language series. The
difference is that instead of declaring the type-name as part of the
initialization grammar, when instantiating anonymous types you instead
just leave the type-name blank after the "new" keyword:
Figure 7
The compiler will parse the above syntax and automatically
define a new standard CLR type that has 4 properties. The types of
each of the 4 properties are determined based on the type of the
initialization values being assigned to them (for example: in the sample above
the "Id" property is being assigned an integer - so the compiler will
generate the property to be of type integer).
The actual CLR name of the anonymous type will automatically
be generated by the C# compiler. The CLR itself actually doesn't know the
difference between an anonymous type and a named type - so the runtime
semantics of the two are absolutely identical. Bart De Smet has
a good blog post here that details this if you want to see
the exact class name pattern and IL generated.
Note above how when you type "product." on the
anonymous type, you still get compile-time checking and full intellisense
within Visual Studio. Notice also how the intellisense description
indicates it is an "AnonymousType" - but still provides full
declaration information of the properties (this is the text circled in red).