Anonymous Types in C# 3.0 and VB9

Sun, February 18, 2007, 06:38 PM under dotNET | Orcas | LINQ
Recall local variable type inference (and the VB9 story) and object initialisers? Here is a reminder:
var o = new SomeType(); //inference
SomeType o = new SomeType {SomeField=DateTime.Now, AnotherField=5.6}; //initialisers
We can of course combine them:
var o = new SomeType {SomeField=DateTime.Now, AnotherField=5.6};
...or in VB if you prefer:
Dim o = New SomeType With {.SomeField = DateTime.Now, .AnotherField = 5.6}
Now, imagine that you were only using variable o in a single method. Also imagine that the type of o (SomeType) only has public fields/properties and no other methods/functions. Also imagine that SomeType was not used anywhere outside that single method. I know all this requires vivid imagination but humour me and picture that scenario.

Well, in the imaginary scenario, you really don't need to declare/define the type! Think about it, why would you need to know what type o is? All you need to be able to do is create something that looks like it and access the public fields/properties. That is exactly what the “anonymous types” feature offers:
var o = new {SomeField=DateTime.Now, AnotherField=5.6};
In VB:
Dim o = New With {.SomeField = DateTime.Now, .AnotherField = 5.6}
In the code above, the compiler generates a class for us, which is visible in IL. The name of the type is not visible to our code and the name is not otherwise usable. Hence we call the feature: anonymous types. If you use your favourite disassembler you can see what the name of the type is but that information will be of academic value.

Another featurette of anonymous types is that the compiler can infer the field names so if you amend the code above like this:
var o2 = new {DateTime.Now, AnotherField=5.6};
In VB:
Dim o2 = New With {DateTime.Now, .AnotherField = 5.6}
...then the anonymous type will have a property called Now that has the value of DateTime.Now and this will of course show up in intellisense e.g. Console.WriteLine(o.Now);

Also note that anonymous types override the ToString method and return something sensible in the format “{Field1 = value1, Field2 = value2}”

Of the three new language features that I've described so far, anonymous types looks like the most useless. Stick with this one for a while. When I bring it all together for LINQ, you'll see the usefulness of the feature.