Dare Obasanjo on C# Anonymous Types
Dare Obasanjo recently wrote a blog entry comparing some language features commonly associated with ‘dynamic’ languages with C# 3.0 equivalents. Towards the end is a section called “Python vs. C# 3.0: Tuples and Dynamic Typing vs. Anonymous Types and Type Inferencing.” In it, he complains that he ended up needing to use nominal types, instead of anonymous types. For example, he wrote:
var vote = new Vote() { Weight = voteFunc(item), Item = item, FeedTitle = feedTitle };
This required him to define the Vote class somewhere. He had been hoping to use C#’s anonymous types, which would have removed the need to define the Vote class explicitly, letting him write:
Also see: Note to self: Blog about using Service Broker
var vote =
{
Weight = voteFunc(item),
Item = item,
FeedTitle = feedTitle
};
He couldn’t do this because his code structure prevented the anonymous type flowing to where he needed it. The first part of his code was a loop which added a bunch of these votes to a list which he later wanted to iterate through. The anonymous type was buried in the nested scope of the first loop, and was therefore inaccessible in the second loop. The fundamental problem here is that C# type inference for ‘var’ variables occurs at the point of declaration. The compiler isn’t prepared to wait around and see what you do with the variable – if it can’t infer the type at the point of declaration it gives up with an error.
