Back to C# Language Enhancements.Anonymous Types allow you to create a type on-the-fly at compile time. The type built has public properties and backing fields defined for the members you initialize during construction. There is no ability to add or customize methods, these types are simply for quickly defining entity types that just hold data.
Anonymous Types use the Object Initializer to specify what properties the new type will be declare. This allows us to reduce code looking similar to this:
class ConcreteType {
private int _x;
private int _y;
public int X {
get { return _x; }
set { _x = value; }
}
public int Y {
get { return _y; }
set { _y = value; }
}
}
ConcreteType conType = new ConcreteType();
contype.X = 1;
contype.Y = 2;
To:
var anonType = new {X = 1, Y = 2};
The actual type assigned to anonType is up to the compiler, and any variable assigned an anonymous type must be declared using the
var keyword so the compiler can assign the name at compile-time (which is the first time it is known). This also means that anonymous types cannot be passed to another method; they can only be used within the method they were declared.
An optimization by the compiler ensures no duplication of identical type structures. This means that if you build an Anonymous Type that has two properties, x and y, then all other anonymous types is defined with an x and y property will share the same compiler built type.
EditReferences
Google search: Anonymous Types C#