Monday, December 10, 2007

C# 3.0: Anonymous Types

C# 3.0 Anonumous types is a nice feature. you can create the object for the class without declaring the class, private variables or properties. suppose if you want to create a class with two properties,

Conventional Method:

class Customer
{

#region Automatic Properties

public long CustomerID
{
get;
set;
}

public string Name
{
get;
set;
}

#endregion
}


Object Creation:

Customer custm = new Customer();
custm.CustomerID = 1;
custm.Name = "Rich";


C# 3.0 Anonymous Types:

you can create a object for the anonymous class(No Class Name) with property initialization.


var cust = new { CustomerID = 1, Name = "Rich" };

The above code will create the object for Anonymous class with two properties of CustomerID and Name.

Visual Studio provides the intellisense for anonymous object without compiling.

Compiler will create the class(Anonymous) for anonymous object like(not exact) the below.


class Anonymous_1
{

public long CustomerID
{
get;
set;
}

public string Name
{
get;
set;
}

}

if you create the multiple anonymous object, compiler will use the same class if type of the property is same.


var cust = new { CustomerID = 1, Name = "Rich" };

var cust1 = new { CustomerID = 2, Name = "David" };

From the above code, compiler will use the same anonymous class for creating the object.


var cust = new { CustomerID = 1, Name = "Rich" };

var cust1 = new { CustomerID = "2", Name = "David" };


From the above code, compiler will use the two class for each object because second anonymous object of property CustomerID type differ from first object.


Once you created the anonymous type object, you can't reassign the value for the property of anonymous type object.

cust.CustomerID = 3;

The above code will throw compiler error.

1 comment:

Anonymous said...

Thanks for this clearly-written post (found through a search engine).