Monday, 6 August 2007

Anonymous Types

I am going to be quite short in this article because I think Daniel Moth's article can explain anonymous types better than i can. However to be complete i will give a short explanation.

Anonymous Types as the name suggests allows you to create a strongly typed object without declaring the class in the first place (this does rely strongly on local variable type inference and Object Initalisers).

For example:



var mailingListSubscriber = new {emailAddress="a@a.com", spamMe=true};


The cool thing about the example above is that mailingListSubscriber now has full intellisense within Visual Studio. At first I thought that was pretty amazing but if you think about what is happening behind the scenes it makes sense.

The anonymous type is not a latebound object, it is a strongly typed object which is autogenerated behind the scenes by the C# Compiler (open up ildasm and have a look for yourself). This means in reality there is no difference (to the CLR) between an anonymous type and a normal type.




Anonymous Types are restricted in the fact that they can only be used within the scope of a local method. This isn't a restriction imposed by the CLR (as i said the CLR doesn't care), but by the C# Compiler. This is a good restriction though, otherwise us developers would end up writing some unmaintainable crazy nonsense code. So thank you C# team for protecting us (from ourselves).

Is an autogenerated, local scoped, undeclared class useful? Damn straight it is, it is one of the many key features that makes LINQ work. I doubt you will ever use Anonymous Types outside of LINQ queries but boy are they useful there (You will notice anonymous types when using the select part of a LINQ query). Using Anonymous Types within LINQ allows you to focus on interacting with the data (in a safe and strongly typed manner) and forget about unneccasary object declarations, or worry about runtime issues with untyped objects.

I will no doubt discuss LINQ in more detail in one of my future blog posts.

Again thanks to Daniel Moth at Microsoft for keeping me straight as I voyage around the new features.

No comments: