Pages

Wednesday, December 21, 2011

Anonymous Types in C# 3.0

Anonymous Types allows developers to create a new type on the fly without an explicit declaration of the class. They can easily be explained with the help of an example -
var person0 = new
{
FirstName = "Mahesh",
LastName = "Krishnan",
Height = 182
};
var person1 = new
{
FirstName = "John",
LastName = "Doe",
Height = 165
};
var person2 = new
{
LastName = "Doe",
FirstName = "John",
Height = 175
};

Notice that the syntax makes use of both Implicitly typed variables as well as Object initialization methods that were explained in earlier posts. The new keyword usually is followed by the type that we wish to create, but while creating anonymous types, this is left blank and is followed immediately with a curly bracket as shown above. When the C# compiler sees a new anonymous class declared, it creates a new class under the covers. If we look at the types of these anonymous classes, they will look something like this -

<>f__AnonymousType0`3[System.String,System.String,System.Int32]
<>f__AnonymousType0`3[System.String,System.String,System.Int32]
<>f__AnonymousType1`3[System.String,System.String,System.Int32]



Notice that C# automatically generated the same Type for both person0 and person1, as they contained the same elements in the same order. person2 had a different order of the same elements and so, C# created a new type for it.

Usage rules/restrictions

The properties in Anonymous types are all read only and therefore cannot be modified once they are created.
Anonymous types cannot have methods.
Anonymous types are always assigned to vars. This allows the compiler to assign the right type. But, if Anonymous types are used as return values or as parameters in a function, they will have to be passed in as Objects, as var is not a proper type

Projection

Anonymous types also supports Projection. So, if we have a declaration as shown below -
var LastName = "Nurk";
var FirstName = "Fred";

var person4 = new { LastName, FirstName};

then a new Anonymous type will be created with the read only properties LastName and FirstName. C# automatically projects the names of the variables to the names of properties in the anonymous class.

This also works while using objects, as shown below -

Person personObject = new Person
{
LastName = "Doe",
FirstName = "Jane",
Height = 156
};
var projectionFromClass = new
{
personObject.FirstName,
personObject.LastName
};

In this case, the object projectionFromClass will have an anonymous type that picks up the property names FirstName and LastName, which will hold the values “Jane” and “Doe”.

No comments: