Anonymous Types

As their name implies, anonymous types are .NET objects that have no name and can be generated on-the-fly. They were first introduced with .NET Framework 3.5, and their main purpose is collecting data from LINQ queries. Generally you prefer named types to anonymous types outside particular LINQ scenarios; however, it’s important to understand how anonymous types work. Declaring an anonymous type is straightforward, as shown in the following code snippet:

image

As you can see, no name for the new type is specified, and a new instance is created just invoking the New With statement. Creating an anonymous type takes advantage of two previously described features, object initializers and local type inference. Object initializers are necessary because anonymous types must be generated in one line, so they do need such a particular feature; local type inteference is fundamental, because you have no other way for declaring a new type as an anonymous type, meaning that only the compiler can do it via local type inference. This is the reason why declaring an anonymous type cannot be accomplished using the As clause. For example, the following code throws an error and will not be compiled:

image

Local type inference is also necessary for another reason. As you can see, you can assign but not declare properties when declaring an anonymous type. (FirstName, LastName, Age, and Email are all properties for the new anonymous type that are both implemented and assigned.) Therefore, the compiler needs a way to understand the type of a property and then implement one for you, and this is only possible due to the local type inference. In the preceding example, for the FirstName, LastName, and Email properties, the compiler infers the String type, whereas for the Age property it infers the Integer type. When you have an anonymous type, you can just use it like any other .NET type. The following code provides an example:

image

As previously mentioned, you can work with an anonymous type like with any other .NET type. The difference is that anonymous types do not h1ave names. Such types can also implement read-only properties. This can be accomplished using the Key keyword with a property name, as demonstrated here:

image

In this example the Age property is treated as read-only and therefore can be assigned only when creating an instance of the anonymous type. You probably wonder why anonymous types can be useful. You get more practical examples in Part 4, “Data Access with ADO.NET and LINQ.”

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

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