something to mention for answering:
Don\'t worry about variance, while the item in question is Array
rather than
I think one reason why Array
doesn't implement that indexer directly is because all the specific array types (like char[]
) derive from Array
.
What this means is that code like this would be legal:
char[] array = new char[10];
array[0] = new object();
Code like this shouldn't be legal, because it's not type-safe. The following is legal and throws an exception:
char[] array = new char[10];
array.SetValue(new object(), 0);
But SetValue()
is not normally used, so this is not a big problem.
C# Specs "12.1.1 The System.Array type" says, "Note that System.Array is not itself an array-type"
Because it is not an array type.
And note that "6.1.6 Implicit reference conversions" says, "From a single-dimensional array type S[] to System.Collections.Generic.IList and its base interfaces, provided that there is an implicit identity or reference conversion from S to T"
C# Specs: http://www.microsoft.com/en-us/download/details.aspx?id=7029
About why the indexer access is so much of a mystery, check this other SO post: implicit vs explicit interface implementation
hope it helps.
Short answer:
System.Array is a base class for N-D arrays (not only 1-D), that's why 1-D indexer (object this[i]{get;set;}) cannot be a base member.
Long answer:
If you let's say create 2-dimensional array and try to access it's IList indexer:
Array a;
a=Array.CreateInstance(typeof(char), 1,1);
(a as IList)[0]='a';
You will get not supported exception.
Good question would be:
Why
System.Array
implementIList
andIEnumerable
while most of its implementation will throwNotSupportedException
for non 1-D array??
One more interesting thing to mention. Technically non of the arrays have class-indexer internally in classic meaning. Classic meaning of Indexer is a property "Item" + get(+set) method(s). If you go deep to reflection you will see that typeof(string[]) does not have indexer property and it only has 2 methods Get and Set - those method declared in string[] class (not in base class, unlike Array.SetValue, Array.GetValue) and they are used for compile-time indexing.