Monday, 5 September 2011

Anonymous Types in C# 3.0


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 dot (“.”) Visual Studio 2008 IntelliSense will show me the two properties: CustId and CustName.

No comments:

Post a Comment