jump to navigation

Anonymous types in C# 3.0 July 7, 2008

Posted by fofo in .NET, C#, c# 3.0, LINQ.
Tags: ,
trackback

In this post I am going to talk about anonymous types which is a new feature that is introduced with C# 3.0.

Anonymous types are particularly useful when querying and transforming data with LINQ.

To understand better about anonymous types I would suggest that you have a look at this post of mine that talks about object initialisers and this one that talks about implicitly local variables .

If I wanted to write a class to represent some data for cars in previous versions of C# I would write

class TheCar{

private string make;

public string Make { get { return make; }

set { make = value; }

}

private string model;

public string Model { get { return model; }

set { model = value; } }

}

To create an instance of this class and set the properties we would write

TheCar mycar = new TheCar();
mycar.Make = “Fiat”;

mycar.Model = “Fiat Punto”;

Using the object initialisation syntax we can write the following statement

var mycar=new TheCar{Make=”Fiat”,Model=”Fiat punto”}; 

With anonymous types I would rewrite the statement above to this

var mycar=new {Make=”Fiat”,Model=”Fiat punto”}; 

As you noticed I did not have to declare a type for this object, thus the name Anonymous.

The compiler creates a class definition in the background.The type name is known to the compiler but it is not available in our source code.
Imagine that there are sometimes that we do not need to know the type of the object. In cases like that we can use anonymous types. To give a more formal definintion we could say that:

1)Launch Visual Studio 2008 and create a simple asp.net web application in C#
2) Add a new item-class to your project and call it TheCar.cs. The code inside this class file should be like this

public class TheCar

{

public string Make { get; set; }

public string Model { get; set; }

public DateTime orderdate { get; set; }

public int milesofar { get; set; }

 public TheCar()

{

//

// TODO: Add constructor logic here

//

}

}

  

3) In the page load event of the default.aspx page type the following

TheCar mycar = new TheCar { Make = “fiat”, Model = “fiat punto”, milesofar = 1234, orderdate = DateTime.Parse(“12/12/2007”) };

Response.Write(mycar.GetType());

Response.Write(“</br>”);

 

var mycar1 = new TheCar { Make = “bmw”, Model = “bmw cabrio”, milesofar = 6556, orderdate = DateTime.Parse(“12/12/2006”) };

Response.Write(mycar1.GetType());

Response.Write(“</br>”);

var mycar2 = new { Make = “mercedes”, Model = “mercedes sl”, milesofar = 1834, orderdate = DateTime.Parse(“02/12/2006”) };

Response.Write(mycar2.GetType());

Basically I instantiate 3 different objects(mycar,mycar1,mycar2) and check their types.

 

Run your application. In the the first two lines you will see in the web page that is created the values TheCar
In the third instance you will see

<>f__AnonymousType0`4[System.String,System.String,System.Int32,System.DateTime]

As you can see there is no name for this type. The compiler generates automatically a name from whatever it is able to infer about this classe’s structure.If we add this 2 lines of code in our page load event handler

 

var mycar3 = new { Make = “opel”, Model = “opel astra”, milesofar = 1134, orderdate = DateTime.Parse(“02/02/2007”) };

Response.Write(mycar3.GetType());

and run again the application.The compiler generates the following result

 

<>f__AnonymousType0`4[System.String,System.String,System.Int32,System.DateTime]

 We can see that as far as the compiler is concerned they are exact the same type.

In case we want to add another property in our object as the code below shows,

var mycar4 = new { Make = “opel”, Model = “opel astra”, milesofar = 1134, orderdate = DateTime.Parse(“02/02/2007″), owner=”George” };

Response.Write(mycar4.GetType());

when we run our application we will get this message
 

<>f__AnonymousType1`5[System.String,System.String,System.Int32,System.DateTime,System.String]

As we can see this is new type for the compiler. This type is different than the previous two.

Even if we change the order of the properties as the code below shows

var mycar5 = new { Model = “opel astra”, Make = “opel”, milesofar = 1134, orderdate = DateTime.Parse(“02/02/2007”)};
Response.Write(mycar5.GetType());
 

When we run the application we will get

<>f__AnonymousType2`4[System.String,System.String,System.Int32,System.DateTime]

This type is different than the previous ones. The compiler automatically generates a new type for this object.

In case we instantiate the new object but change the property names like the code below shows

var mycar6 = new { myModel = “opel astra”, myMake = “opel”, mymilesofar = 1134, myorderdate = DateTime.Parse(“02/02/2007”) };
Response.Write(mycar6.GetType());

and run the application we will get

<>f__AnonymousType3`4[System.String,System.String,System.Int32,System.DateTime]

Because the properties are named different the compiler will create a brand new type-class.

Hope this post helps you to understand anonymous types. It will make sense when we use them with LINQ

 

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to Ma.gnoliaAdd to TechnoratiAdd to Furl

Comments»

1. Viktar Karpach | Web Developer Blog - November 6, 2008

Nice feature. Since types are the same can be used not only with LINQ.


Leave a comment