Search code examples
c#arraysicollection

Array doesn't implement ICollection<T> but is assignable


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>!


Solution

  • 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.