Wriju's BLOG

.NET, Cloud and everything

C# 3.0 : Anonymous Types

C# 3.0’s Anonymous Type is a cool feature and it allows us to create object and collection of no type. Actually the type does not exist but on the fly you can create object out of that type. Let’s say you need to create some object which will have two properties Id of type int and Name of type string. In normal scenario, you have to write a class and then create the object of that class. But C# 3.0 allows us to declare an object of that type and assign value to it.


Suppose you need this Class


public class Cust


    public int CustId { get; set; }


    private string _CustName;

    public string CustName


        get { return _CustName; }

        set { _CustName = value; }




But you are too lazy to create the class. This C# 3.0 will create this class for you. So if you write something like


var obj = new { CustId = 1, CustName = “C#” };




Notice here after the keyword “new” I have no type name. This gives instruction to the compiler to create a dummy type for me. Now Visual Studio is so exciting that this does not require me to compile to be able to provide me the IntelliSense support. Without compiling I can get the IntelliSense and auto complete.


Whenever I will use obj and after the “.” Visual Studio 2008 IntelliSense will show me the two properties,




One of the drawbacks is that you cannot reset the property value. So if you try to write, obj.CustId = 1; will through you an error.


Property or indexer ‘AnonymousType#1.CustId’ cannot be assigned to

— it is read only  


This is because it creates get-only property and can only be initialized through the Object Initializers feature of C# 3.0.


Another observed behavior is that if you create object with the keyword “new”, like,


var obj = new { CustId = 1, CustName = “C#” };


var obj2 = new { Id = 1, Name = “C#” };





Now the compiler will create two anonymous types as the property name differs.




If you use objects like,


var obj = new { CustId = 1, CustName = “C#” };


var obj1 = new { CustId = 1, CustName = “C#” };


Compiler will not create multiple types as the name is same.




Interestingly if you have declarations like,


var obj = new { CustId = 1, CustName = “C#” };


var obj1 = new { CustId = “A”, CustName = “C#” };


var obj2 = new { CustId = 2.2, CustName = “C#” };



The CLR will create only one Type, but the compiler will give you three different date type options for the three objects.



For obj the CustId will be inferred as type “int”.



For obj1 the CustId will be inferred as type “string”.




For obj2 the CustId will be inferred as type “double”.


This is because the generated IL creates the type as Generic type. With the


.field private initonly !'<CustId>j__TPar’ ‘<CustId>i__Field’


“initonly” is readonly and “!” indicates that the type is generic.