something to mention for answering:
Don\'t worry about variance, while the item in question is Array
rather than
The problem with IList
's methods in the Array
class, including its indexer, is that their explicit implementations are added to Array objects of the class at run time:
Starting with the .NET Framework 2.0, the
Array
class implements theSystem.Collections.Generic.IList
,System.Collections.Generic.ICollection
, andSystem.Collections.Generic.IEnumerable
generic interfaces. The implementations are provided to arrays at run time, and therefore are not visible to the documentation build tools. As a result, the generic interfaces do not appear in the declaration syntax for theArray
class, and there are no reference topics for interface members that are accessible only by casting an array to the generic interface type (explicit interface implementations).
When classes implement interfaces explicitly, accessing interface methods requires a cast:
A class that implements an interface can explicitly implement a member of that interface. When a member is explicitly implemented, it cannot be accessed through a class instance, but only through an instance of the interface.
The problem with providing a "regular" (as opposed to an "explicit") interface implementation is the fact that the Array
class is not generic: without a type parameter, you cannot write
class Array : IList
simply because T
is undefined. The environment cannot slap an interface implementation onto the Array
class until the type of the T
parameter becomes known, which may happen only at run time:
// The type of [T] is char
Array a = Array.CreateInstance(typeof(char), 1);
// The type of [T] is int
Array b = Array.CreateInstance(typeof(int), 1);
// The type of [T] is string
Array c = Array.CreateInstance(typeof(string), 1);
At the same time, the static type of a
, b
, and c
remains the same - it's System.Array
. However, at run time a
will be implementing IList
, b
will be implementing IList
, and c
- IList
. None of it is known at compile time, prevents the compiler from "seeing" the indexer and other methods of IList
.
Moreover, not all instances of Array
implement IList
- only arrays with a single dimension do:
Array x = new int[5];
Console.WriteLine(x.GetType().GetInterface("IList`1") != null); // True
Array y = new int[5,5];
Console.WriteLine(y.GetType().GetInterface("IList`1") != null); // False
All of the above prevents the compiler from accessing IList
methods, including the indexer, without an explicit cast.