CSharp/C# Tutorial - C# Anonymous Types






An anonymous type is a class created by the compiler on the fly to store a set of values.

To create an anonymous type, use the new keyword followed by an object initializer, specifying the properties and values the type will contain.

Example

For example:


var person = new { Name = "Jack", Age = 23 };

You must use the var keyword to reference an anonymous type, because it doesn't have a name.

The property name of an anonymous type can be inferred from an expression. For example:


int Age = 3;
var person = new { Name = "Jack", Age, Age.ToString().Length };

is equivalent to:


var person = new { Name = "Jack", Age = Age, Length = Age.ToString().Length };

Two anonymous type instances declared within the same assembly will have the same underlying type if their elements are named and typed identically:


var a1 = new { X = 2, Y = 4 };
var a2 = new { X = 2, Y = 4 };
Console.WriteLine (a1.GetType() == a2.GetType()); // True

Equals method is overridden to perform equality comparisons:


Console.WriteLine (a1 == a2); // False
Console.WriteLine (a1.Equals (a2)); // True

You can create arrays of anonymous types as follows:


var persons = new[]{
    new { Name = "A", Age = 3 },
    new { Name = "B", Age = 4 }
};