Using a collection initializer in my own class

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

I will quote the important part that puzzles me:

Collection initializers allow you to specify one or more element initializers when initializing a collection class that implements IEnumerable or the class using the Add extension method.

Good, so I want to emphasize the word or . When I read it, I would have to create a class using the Add method, and then the collection initializer should work on this class? This does not seem to be the case. One thing I noticed was that it actually speaks of a method of adding an extension. So I tried to create the Add As Extension method, but to no avail.

Here is a small example that I tried that does not work:

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

Is citation subject to other interpretations than mine? I tried to read it again and again to see if I could interpret it in any other way, but I could not do it.

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

+6
source share
1 answer

It should be an β€œand,” not a β€œor."

Collection initializers are described in the C # Language Specification , Section 7.6.10.3 Collection Initializers:

The collection object to which the collection initializer is applied must be of a type that implements System.Collections.IEnumerable or a compile-time error occurs. For each element specified, in order, the collection initializer calls the Add method on the target with a list of element initializer expressions as a list of arguments, using the normal overload resolution for each call. Thus, the collection object must contain the applicable Add method for each element initializer.

It clearly states that the collection must implement IEnumerable and there must be an Add method. Calling the Add method is allowed using the normal overload resolution process, so it can be an extension method, a general method, etc.

+4
source

All Articles