Prash's Blog

Using Anonymous types in .Net 3.0 September 28, 2009

Filed under: C# — prazjain @ 2:20 am
Tags: ,

Using Anonymous types in C# .Net 3.0

Anonymous types should as simple containers for storing temporary data. These types as they do not have a name associated with them, cannot be passed to a method or returned back. Generally these are supposed to be used inside a method while performing some processing, where you would not like to work on the entire data structure and just a part of it.

How to create an anonymous type

</p>
<p>var anonTypeVar = new { X = 100, Y = 200 };</p>
<p>

This statement causes compiler to generate an internal sealed class, with readonly properties for X and Y. The constructor for this class takes two parameters for each property, in the sequence they are defined. The type of the properties is determined by their values.
eg. : This is approximately what compiler generates behind the scenes.

</p>
<p>internal sealed AnonTypeClass {<br />
private readonly int x;<br />
public int X { get { return x; } }</p>
<p>private readonly int y;<br />
public int Y { get { return y; } }</p>
<p>public AnonTypeClass(int xParam, int yParam) { x = xParam ; y = yParam; }</p>
<p>}</p>
<p>

The compiler generates this boiler plate code for you when you create an anonymous type var.

In case you noticed by now, using object initializers with immutable types is only possible when its an anonymous type, as compiler adds some features into the auto-gen code to allow that.

You might be tempted to think that the compiler create a new type everytime it sees that expression. No, it reuses the same type as long as their are same number of properties, they are of same type, same name, and in the same sequence.
So these expressions would generate different types :

</p>
<p>var a1 = new { X = &quot;a&quot;, Y = &quot;b&quot; };<br />
var a2 = new { Y = 100, X = 200 };<br />
var a3 = new { X = 100, Y = 200, Z = 300 };</p>
<p>

Overuse of anonymous types could make the code unreadable, but if used judiciously they could prevent creation of lots of classes that are used to create only temporary objects  in intermediate processing.

Advertisements
 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s