Opinion: Collection Initializers Syntax

Mads Torgersen wrote last month in his weblog about how collections are identified by C# 3.0’s new feature – Collection Initializers. You should go read what they are – good stuff. I’d like to address one of the side-topics in his post – overload selection. Let’s take Mads’s example:

public class Plurals : IDictionary<string,string> { public void Add(string singular, string plural); // implements IDictionary<string,string>.Add public void Add(string singular); // appends an “s” to the singular form public void Add(KeyValuePair<string,string> pair); // implements ICollection<KeyValuePair<string,string>>.Add // } Plurals myPlurals = new Plurals{ “collection”, { “query”, “queries” }, new KeyValuePair(“child”, “children”) };

The last line is converted by the compiler to:

Plurals myPlurals = new Plurals(); myPlurals.Add(“collection”); myPlurals.Add(“query”, “queries”); // <- Marked Line myPlurals.Add(new KeyValuePair(“child”, “children”));

I’d like to address the marked line. As you can see, the line calls the overload that takes a (string, string) tuple. The collection initializer, however, gets what looks to be an array of two strings.

At first, I was confused and did not understand what this meant, so I asked why not just use the simple parentheses, to which Mads replied:

As for the curly syntax for multiple arguments, let it be no secret that parentheses and curlies were both strong candidates. Both are also already overloaded. Omer’s comment outlines that clearly for curlies; however, parentheses are also already heavily used; for grouping, invoking, casting etc. Curlies have the advantage of not falsely suggesting that we have tuples in the language.

Since C# is my main language and I believe it should remain consistent, my answer to this was:

You mention invoking and this is exactly the situation here – you’re invoking an overload. You can say that the pure mathematical definition of a function dictates that the above pair is a tuple and that the language doesn’t have them, but the fact remains that this is a method call and not a type initialization (I’m talking about only the query/queries part) which would make the use of curly brackets inconsistent with the rest of the language (which uses curly brackets for initialization: anonymous types, collection initializers, array initializers, anonymous methods, etc.).

What’s your take on this?


One thought on “Opinion: Collection Initializers Syntax

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s