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.

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.

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.


One thought on “C# and anonymous types

Leave a Reply

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