Gunnar Peipman's ASP.NET blog

ASP.NET, C#, SharePoint, SQL Server and general software development topics.

Sponsors

News

 
 
 
 
 
DZone MVB

Links

Social

C# and anonymous types

One cool feature of C# 3.0 is support of anonymous types. Let's suppose we have to create some data structure and we need this structure in one place in one method. This far we had to create a new private class or structure. With anonymous types we don't have to define new type - we can create it on the run.

Let's create a simple anonymous type for rectangle. The code is as follows and let's suppose it makes some calculations using dimensions of object.


...

var rectangle = new { Width=x, Height=y };

...

return density;


As we can see there is no type specified for rectangle. Instead type we have plain definition of object. This definition is also supported by IntelliSense.

Anonymous types are supported by IntelliSense

If we look at previous picture we can see that our new variable has all the properties that objects have. It is inherited from object class. Let's see now what compiler produced us.

Structure of anonymous type

As we can see there is new type called <>f__AnonymousType0`2 defined. This is our rectangle. The other classes are not able to inherit from our rectangle and also it is not possible to recreate this type in code again. This new type is created after compilation and it doesn't exist until compilation.

Anonymous types may be very useful if we need some temporary structures to organize our data better. Anonymous types must be used very carefully because otherwise they may mess up your code and make readability worst. Therefore it is good idea to use anonymous types carefully.

Comments

Gunnar Peipman's ASP.NET blog said:

I wrote unit tests for my ASP.NET MVC application that uses some jQuery AJAX-components. These components

# July 24, 2010 8:26 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)