Sunday, August 26, 2007 12:00 AM
bart
Visual Basic 9.0 Feature Focus - Anonymous types
Welcome back to the Visual Basic 9.0 Feature Focus blog series. In this post, we'll cover Anonymous types, a feature also available in C# 3.0. The need for anonymous types originates from projection clauses in LINQ statements which typically cook up a new ad-hoc type containing the data of interest. Nevertheless, anonymous types are useful in isolation too, for instance to group a couple of variables together without having to build a special type for that sole purpose.
Anonymous type syntax is similar to Object Initializer syntax (see previous post in my Visual Basic 9.0 Feature Focus series) and looks like this:
Dim t = New With {.Name = "Bart", .Age = 24}
The part between the curly braces can contain an arbitrary number of initializers which follow the syntax conventions of With (i.e. starting with a dot). Notice this is a place where Implicitly Typed Local Variables are required in order to declare a variable of the anonymous type (which has some compiler-generated unspeakable name like VB$AnonymousType_0`2).
Notice the type overrides ToString which produces a comma separated key/value pair string between curly braces, like "{ Name = Bart, Age = 24}". The compiler is also smart enough to infer the name of the to-be-generated property if you're referring to another already-existing property, like this:
Dim t = New With {.Name = "Bart", .Age = 24}
Dim id = 123
Dim u = New With {.Id = id, t.Name, t.Age}
where the latest statement is equivalent to:
Dim u = New With {.Id = id, .Name = t.Name, .Age = t.Age}
One thing unique to VB 9.0 is the existence of so-called keyed anonymous types. In the previous samples, the Equals method will only return true if you're comparing two identical references with one another. Therefore, the following will print False:
Dim t = New With {.Name = "Bart", .Age = 24}
Dim u = New With {.Name = "Bart", .Age = 24}
Console.WriteLine(t.Equals(u))
even though both anonymous types denote the same "shape" and have the same values assigned. If you define one or more properties as a key using the Key keyword (that's a lot of keys in this sentence), these are used for the equality check (Equals) and the creation of a hash code (GetHashCode). Here's a sample that will print True:
Dim t = New With {Key .Id = 1, .Name = "Bart", .Age = 24}
Dim u = New With {Key .Id = 1, .Name = "Anders", .Age = 47}
Console.WriteLine(t.Equals(u))
Both objects are the same because (all) the keys are equal: only the fields marked with Key are compared to do the equality test. Geeks can check this easily using ILDASM.
We'll encounter anonymous types again when talking about LINQ query syntax later in this series. A little sample of a projection inside a VB 9.0 LINQ query is shown below:
Dim res = From c In customers Select New With {c.Name, c.Age}
Happy coding!
Del.icio.us |
Digg It |
Technorati |
Blinklist |
Furl |
reddit |
DotNetKicks