1.7. Anonymous Types

In Listing 1-1, note that no type was specified after the new keyword in the object initialization expression. The compiler created a locally scoped anonymous type for us.

Anonymous types let us work with query results on the fly without having to explicitly define classes to represent them. When the compiler encountered

select new { p.FirstName, p.LastName };

in Listing 1-1 it transparently created a new class with two properties, one for each parameter (see Listing 1-7).

Example 1-7. A Class for an Anonymous Type
internal class ???
{
    private string _firstName;
    private string _lastName;

public string FirstName {
        get { return _firstName; }
        set { firstName = value; }
    }
    public string LastName {
        get { return _lastName; }
        set { lastName = value; }
    }
}

As you can see in Listing 1-7, the property names are taken directly from the fields specified in the Person class. However, you can indicate the properties for the anonymous type explicitly using the following syntax:

new { firstName = p.FirstName, lastName = p.LastName };

Now to use the anonymous type in the code you have to respect the new names and the case-sensitive syntax. For example, to print the full name you would use the following:

Console.WriteLine("Full Name = {0} {1}", query.firstName, query.lastName);

Keep in mind that the anonymous type itself cannot be referenced from the code. How is it possible to access the results of a query if you don't know the name of the new type? The compiler handles this for you by inferring the type. We'll look at this next.

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

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