Anonymous types in C#

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 and IntelliSense

Anonymous types after compiling

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. For this we use ILDASM tool by Microsoft.

Anonymous types in ILDASM

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.

Wrapping up

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. Find out more about anonymous types from Microsoft documentation about it.

More compiler secrets

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    Leave a Reply

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