Search code examples
c#msdncollection-initializer

Using collection initializer on my own class


I am trying to add collection initializing to my class. I read about the initializers here: https://msdn.microsoft.com/en-us/library/bb384062.aspx#Anchor_2

I'll quote the important part that puzzles me:

Collection initializers let you specify one or more element initializers when you initialize a collection class that implements IEnumerable or a class with an Add extension method.

Ok, so I want to emphasize on the word or. As I read it, I should be able to make a class with an Add method, and then the collection initializer should work on this class? This doesn't seem to be the case. One thing I did note, was that it does in fact say an Add extension method. So I tried creating the Add as an extension method as well, but to no avail.

Here's a small sample I tried that does not work:

public class PropertySpecificationCollection
{
    private List<PropertySpecification> _internalArr;
    public void Add(PropertySpecification item)
    {
        _internalArr.Add(item);
    }
}

Is the quote subject to other interpretations than mine? I tried reading it over and over again, to see if I could interpret it in any other way, but failed to do so.

So I guess my question is: Am I interpreting it wrong, am I missing something, or is there an error in the description of collection initializers on MSDN?


Solution

  • It should be "and", not "or".

    Collection initializers are described in C# language specification, section 7.6.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.

    It clearly states that the collection must implement IEnumerable and there needs to be an Add method. The call to the Add method is resolved using normal overload resolution process, so it can be an extension method, generic method etc.