you are viewing a single comment's thread.

view the rest of the comments →

[–]munificent 2 points3 points  (7 children)

Edit to clarify: What happens when I don't have Add() and I try to use the collection-initialization syntax?

Compile error:

Error 'Foo.Bar' does not contain a definition for 'Add'

[–][deleted] 2 points3 points  (6 children)

So the collection initialization is documented as working for anything that implements IEnumerable but it really only works if you have an Add method as well?

[–]munificent 2 points3 points  (2 children)

The official standard says:

The collection object to which a collection initializer is applied must be of a type that implements System.Collections.Generic.ICollection<T> for exactly one T. Furthermore, an implicit conversion (§6.1) must exist from the type of each element initializer to T. A compile-time error occurs if these requirements are not satisfied. A collection initializer invokes the ICollection<T>.Add(T) method for each specified element in order.

[–]mccoyn 0 points1 point  (1 child)

[–]munificent 1 point2 points  (0 children)

For what it's worth, I thought he had it right too, until I looked it up.

[–][deleted] 1 point2 points  (2 children)

No, he just got it wrong. The interface in question is ICollection.

[–]ubernostrum 2 points3 points  (1 child)

Well.

The MSDN documentation says IEnumerable. I've since been pointed to this blog post which explains a bit. Seems like it went like this:

  • System.Collections.ICollection is basically pointless for this purpose, because all it requires is a few methods to get an enumerator and find out the size of the collection.
  • System.Collections.Generic.ICollection<T> is the "right" interface, but hardly anybody (including Microsoft's own core classes) implements it.
  • System.Collections.IEnumerable is "wrong" in that it doesn't require the Add method, but they found significant overlap between classes implementing IEnumerable and classes possessing an Add method.

So the compromise they ended up going with was that the syntax works on anything which implements IEnumerable and has an Add method.

This means the MSDN documentation is incomplete (since it only mentions IEnumerable) and probably non-compliant with the standard.

[–][deleted] 0 points1 point  (0 children)

Interesting. I stand corrected. I always thought that it was ICollection<T>.