by Ivo Stoykov
Anonymous Types are useful when we do not need to follow usual work-flow -- creating object of some type, assign some read-only values and then doing something with them. Instead we can encapsulate this read only data into an anonymous type without first defining object explicitly. (Anonymous simply means "without a name".)
Anonymous types are class types that consist of one or more public read-only properties.
In C# 3.0 compiler generates anonymous types through object initializer, who cares to use appropriate types assigning given values to one or more fields or properties of an object. This is why anonymous types are not available in source code level.
Objects declared as anonymous types use the var keyword in place of the type name. Dislike JavaScript the var keyword here always generates a strongly typed variable reference.
Sample:
Note that there is no name for the class. Therefore, in declaration, we cannot specify type in front of the variable. Instead the var keyword is used.
var tells the compiler that we leave to it to infer the type of the variable for us. The var keyword can be used to reference any type in C#. So following declaration
is identical with
Because the var keyword produces a strongly-typed variable declaration, the compiler needs to be able to infer the type to declare based on its usage. This means that you need to always do an initial value assignment when declaring one. The compiler will produce a compiler error if you don't:
Note that in the sample above
the usage of the new keyword. It is used without a type name. What follows the new keyword is the object initializer mentioned previously. It is its duty to create a class for us with declared properties.
So for our v variable it will create
Note that object initializer works out the type from the expression used to initialize the variable when it is first declared.
Sample:
Limitation
Anonymous Type (type = class in this case) are greatly limited compared to standard classes. They can only inherit from object and their only memebers are private fields.