5

Look at this insane piece of code:

ICollection<int> list = new[] {1, 2, 3};
list.Add(4); // NotSupportedException: Collection was of a fixed size.

I'm not wondering about the exception! I'm wondering that a simple array could be assigned to ICollection<T>. I see Array implements IList and ICollection but as far as I know it never implements ICollection<T>!

Marcel
  • 1,002
  • 2
  • 16
  • 37
  • 1
    If the linked question/answer isn't enough to cover what you asked, I (or someone else) will reopen the question – xanatos Feb 26 '16 at 14:16
  • 2
    [Arrays automatically implement `IList`](http://tinyurl.com/z3xwlxb) which implements `ICollection`. It's also mentioned in the [`Array` documentation](http://tinyurl.com/363o4u4) but a bit hidden: _"Starting with the .NET Framework 2.0, the `Array` class implements the `System.Collections.Generic.IList`, `System.Collections.Generic.ICollection`, and `System.Collections.Generic.IEnumerable` generic interfaces. The implementations are provided to arrays at run time, and as a result, the generic interfaces do not appear in the declaration syntax for the Array class."_ – Tim Schmelter Feb 26 '16 at 14:25
  • @TimSchmelter Thanks. That's the answer! – Marcel Feb 26 '16 at 15:19

1 Answers1

6

I see Array implements IList and ICollection but as far as I know it never implements ICollection

It does implement ICollection<T>, the implementation is simply injected at run-time.

From the documentation:

Starting with the .NET Framework 2.0, the Array class implements the System.Collections.Generic.IList<T>, System.Collections.Generic.ICollection<T>, and System.Collections.Generic.IEnumerable<T> generic interfaces. The implementations are provided to arrays at run time, and as a result, the generic interfaces do not appear in the declaration syntax for the Array class. In addition, there are no reference topics for interface members that are accessible only by casting an array to the generic interface type (explicit interface implementations). The key thing to be aware of when you cast an array to one of these interfaces is that members which add, insert, or remove elements throw NotSupportedException.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321