12.3. Anonymous Types
Often when you are manipulating data you may find that you need to record pairs of data. For example, when iterating through people in a database you might want to extract height and weight. You can either use a built-in type (in this case a Point or PointF might suffice) or create your own class or structure in which to store the information. If you do this only once within your entire application, it seems quite superfluous to have to create a separate file, think of an appropriate class or structure name, and define all the fields, properties, and constructors. Anonymous types give you an easy way to create these types using implicit typing, which you have just learned about.
VB.NET
Dim personAge = New With {.Name = "Bob", .Age = 55}
C#
var personAge=new {Name="Bob", Age=55};
In the preceding example, you can see that the personAge variable is being assigned a value that is made up of a String and an Integer. If you were to interrogate the type information of the personAge variable, you would see that it is named "VB$AnonymousType_0'2[System.String,System.Int32]" (or "<>f__AnonymousType0'2[System.String,System.Int32]" in C#) and that it has the properties Name and Age. One of the points of difference between C# and VB.NET is whether these properties are read-only (i.e., immutable) or not. In C# all properties of an anonymous type are immutable, as shown by the IntelliSense in Figure 12-3. This makes generating hash codes simpler. Essentially, if the properties ...
Get Professional Visual Studio® 2008 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.