Skip to Main Content
Professional Visual Studio® 2008
book

Professional Visual Studio® 2008

by Nick Randolph, David Gardner
July 2008
Intermediate to advanced content levelIntermediate to advanced
1026 pages
27h 59m
English
Wrox
Content preview from Professional Visual Studio® 2008

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Professional Visual Studio® 2010

Professional Visual Studio® 2010

Nick Randolph, David Gardner, Michael Minutillo, Chris Anderson

Publisher Resources

ISBN: 9780470229880Purchase book