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.