Custom Collection Initializers

No, the compiler requires a method named Add for the collection initializer to work. This is defined in C# specification and cannot be changed:

C# Language Specification – 7.5.10.3 Collection Initializers

The collection object to which a collection initializer is applied must be of a type that implements System.Collections.IEnumerable or a compile-time error occurs. For each specified element in order, the collection initializer invokes an Add method on the target object with the expression list of the element initializer as argument list, applying normal overload resolution for each invocation. Thus, the collection object must contain an applicable Add method for each element initializer. [emphasis mine]

Of course, the Add method can take more than one argument (like Dictionary<TKey, TValue>):

dic = new Dictionary<int, int> { 
    { 1, 2 },
    { 3, 4 }
};
// translated to:
dic = new Dictionary<int, int>();
dic.Add(1, 2);
dic.Add(3, 4);

Leave a Comment