Anonymous types

With the new feature of the object initializer, and the new var data type, we can create anonymous data types easily in C# 3.0.

For example, if we define a variable like this:

var a = new { Name = "name1", Address = "address1" };

At compile time, the compiler will actually create an anonymous type as follows:

class __Anonymous1
{
private string name;
private string address;
public string Name {
get{
return name;
}
set {
name=value
}
}
public string Address {
get{
return address;
}
set{
address=value;
}
}
}

The name of the anonymous type is automatically generated by the compiler, and cannot be referenced in the program text.

If two anonymous types have the same members with the same data types in their initializers, then these two variables have the same types. For example, if there is another variable defined like this:

var b = new { Name = "name2", Address = "address2" };

Then we can assign a to b like this:

b = a;

The anonymous type is particularly useful for LINQ when the result of LINQ can be shaped to be whatever you like. We will give more examples of this when we discuss LINQ.

As mentioned earlier, this new feature is again a Visual Studio 2008 compiler feature, and compiled assembly is a valid .NET 2.0 assembly.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset