Creating an Instance of a Nonexistent Class

The .NET languages enable you to create an object that does not have a class representation at design time. Instead, an unnamed (anonymous) class is created for you by the compiler. This feature is called anonymous types. Anonymous types provide crucial support for LINQ queries. With them, columns of data returned from a query can be represented as objects (more on this later). Anonymous types are compiled into class objects with read-only properties.

Let’s look at an example of how you would create an anonymous type. Suppose that you want to create an object that has both a Name and a PhoneNumber property. However, you do not have such a class definition in your code. You could create an anonymous type declaration to do so, as shown here.

C#

var emp = new { Name = "Joe Smith",
  PhoneNumber = "123-123-1234"};

VB

Dim emp = New With {.Name = "Joe Smith", _
  .PhoneNumber = "123-123-1234"}

Notice that the anonymous type declaration uses object initializers (see the previous discussion) to define the object. The big difference is that there is no strong typing after the variable declaration or after the New keyword. Instead, the compiler creates an anonymous type for you with the properties Name and PhoneNumber.

There is also the Key keyword in Visual Basic. It is used to signal that a given property of an anonymous type should be used by the compiler to further define how the object is treated. Properties defined as Key are used to determine whether two instances of an anonymous type are equal to one another. C# does not have this concept. Instead, in C# all properties are treated like a Visual Basic Key property. In Visual Basic, you indicate a Key property in this way.

Dim emp = New With {Key .Name = "Joe Smith", _
  .PhoneNumber = "123-123-1234"}

You can also create anonymous types using variables (instead of the property name equals syntax). In these cases, the compiler uses the name of the variable as the property name and its value as the value for the anonymous type’s property. For example, in the following code, the name variable is used as a property for the anonymous type.

C#

string name = "Joe Smith";
var emp = new {name, PhoneNumber = "123-123-1234" };

VB

Dim name As String = "Joe Smith"
Dim emp = New With {name, .PhoneNumber = "123-123-1234"}

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

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