Anonymous Types

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

It is created using the new keyword followed by an object initializer, specifying the properties and values.

You must use the var keyword to reference an anonymous type.

Anonymous types are used mostly when writing LINQ queries.

var dude = new {Name = "Bob", Age = 23};

compiler compiles into:

internal class AnonymousGeneratedTypeName
{
	private string name; // Actual field name is irrelevant
	private int age; // Actual field name is irrelevant

	public AnonymousGeneratedTypeName (string name, int age)
	{
		this.name = name; this.age = age;
	}

	public string Name { get { return name; } }

	public int Age { get { return age; } }


	// The Equals and GetHashCode methods are overridden (see Chapter 6).
	// The ToString method is also overridden.
}
...
var dude = new AnonymousGeneratedTypeName ("Bob", 23);

The property name of an anonymous type can be inferred from an expression that is itself an identifier (or ends with one).

int Age = 23;

// The following:
{
	var dude = new { Name = "Bob", Age, Age.ToString().Length };
	dude.Dump();
}
// is shorthand for:
{
	var dude = new { Name = "Bob", Age = Age, Length = Age.ToString().Length };
	dude.Dump();
}

Two anonymous type instances will have the same underlying type if their elements are same-typed and they’re declared within the same assembly.

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

// Additionally, the 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

var dudes = new[]
{
   new {Name = "Bob", Age = 30},
   new {Name = "Tom", Age = 40}
}

Leave a Reply

Your email address will not be published. Required fields are marked *