Anonymous types

With the feature of the object initializer and the var datatype, we can create anonymous datatypes easily in C#.

For example, we can define a variable as follows:

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 variables that are defined by anonymous types have the same members with the same datatypes in their initializers, these two variables have the same anonymous types. For example, if there is another variable defined as follows:

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

Then we can assign a to b as in the following example:

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 feature is again a Visual Studio compiler feature and the compiled assembly is a valid .NET assembly.

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

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