All posts tagged 'new features'

.NET Musings

Wandering thoughts of a developer, architect, speaker, and trainer


Anonymous Types in VS2008 and C# 3.0

C# 3.0 introduces the ability to create types on the fly. This is interesting, since C# is a strongly typed language. By themselves, this new feature isn’t all that valuable. However, it becomes vital to support the new ability to create types on the fly with LINQ expressions, which will be the subject of my next post.

How do you create an anonymous type? It’s the sum of a couple of new features: Implicitly Typed Variables and Object Initialization. Since there is no concrete type, we must use the var keyword to declare the variable. Likewise, since we don’t have a predefine class with properties, we have to use Object Initialization to set the values and define the properties.

var MyWidget = new
           Name = "Widget1",
           Price = 10.00,
           Description = "My New Widget"

You can then use the new class in your code with a few caveats:

  • All of the properties are read only

  • There can’t be any methods or events coded

  • There can only be a default constructor

  • They can’t be used as parameters

When we look at the class in Reflector, we see that indeed we have a concrete class:


So, there you have. Like I said, by themselves, not much use. But, anonymous types are vital to grokking LINQ.

Happy Coding!

Managed Windows Shared Hosting by OrcsWeb