Cook Computing

infoof and Collection Initializers

November 27, 2011 Written by Charles Cook

While thinking about which features I would like added to C# I came across an old post by Eric Lippert — In Foof We Trust: A Dialogue — in which he presents an imaginary dialog between himself and a C# user who would like an operator or operators similar to typeof() but which would take the name of a method, field, or property instead of a type name. I mentioned something similar in old posts here and here. This feature would certain reduce the need to hard-code method/property names or use lambda expressions, for example in implementations of INotifyPropertyChanged.PropertyChanged, and would help refactoring tools. It was interesting to read:

I agree, that would be a lovely sugar. This idea has been coming up during the C# design meeting for almost a decade now. We call the proposed operator “infoof”, since it would return arbitrary metadata info. We whimsically insist that it be pronounced “in-foof”, not “info-of”.

He goes on to describe that there are design issues which make this much more costly to implement and test than it appears at first sight and that there are always budgetary constraints on which new features his team can deliver. He sums up:

It’s an awesome feature that pretty much everyone involved in the design process wishes we could do, but there are good practical reasons why we choose not to. If there comes a day when designing it and implementing it is the best way we could spend our limited budget, we’ll do it. Until then, use Reflection.

Looks like that one will remain on the wishlist but it turns out that one other feature I would like has already been implemented for some time now: collection initializers for dictionaries. For example, you can write this:

Dictionary<int, string> hashtable = new Dictionary<int, string>
      { { 1, "one" }, {2, "two" }, {3, "three" } };

This is a particular case of using a collection initializer which turns out to be a fairly complicated, not to say contrived, language feature. If your type implements IEnumerable — presumably a sanity check that it represents some sort of collection — and has one or more methods called Add(), the compiler will map the collection initializer expression onto calls to the Add() function(s). Mads Torgerson wrote about this in 2006: What is a collection?