I read and re-read help documentation, white papers, blogs, and tweak and poke around code to find out what is hiding in the crevices. Today I found something that I don’t think I have seen before. You probably know of course that you can define anonymous types with initializers in VB, as shown here:
Dim company = New With {.CustomerID = "PAULK", .CompanyName = "Kimmel's Konfections"}
The preceding code will cause the compiler to generate a class and the names in the initializer list—CustomerID and CompanyName—will be added as properties to the class. The type of these properties will inferred by the values assigned to them.
Did you know that you can nest anonymous type initializers? By using the same notation in the initializer list you can specify nested anonymous types. The following code defines an anonymous class containing a CustomerID and CompanyName and a nested type containing a phone number.
Dim company = New With {.CustomerID = "PAULK", _
.CompanyName = "Kimmel's Konfections", _
.Phone = New With {.Number = "(517) 555-1212"}}
If you write the class to the console you can see the contents as they are logically laid out (see Figure 1). If you look at the anonymous type in Reflector then you can see that the very short statement generates a complete class with, in this case, a nested class (see Figure 2).
Figure 1: The layout of the anonymous type shows that Phone is a nested type.
Figure 2: The anonymous type with the nested type assigned to Phone.