You can now 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 get compiled into class objects with read-only properties.

Let’s look at an example of how you would create an anonymous type. Suppose you want to create an object that had 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:

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

C#
var emp = new { Name = “Joe Smith”,
PhoneNumber = “123=123=1234” };

Notice that the anonymous type declaration uses object initializers 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 will create 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 VB Key property. In VB, 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:

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

C#
string name = “Joe Smith”;
var emp = new {name, PhoneNumber = “123=123=1234” };

Source of Information : Sams Microsoft Visual Studio 2008 Unleashed

0 comments


Subscribe to Developer Techno ?
Enter your email address:

Delivered by FeedBurner