Alex Rivera | Logout

How do Arrays implement IList<T> without implementing the property "Count" in C#?

Asked 2012-09-17T14:22:08.097
26

For a very long time I was curious about the following:

int[] array = new int[1];
int iArrayLength = array.Length;    //1

Since arrays implement the IList interface, the following is allowed:

int iArrayCount = ((IList<int>)array).Count;    //still 1

BUT:

int iArrayCount = array.Count;  //Compile error. WHY?
int iArrayLength = array.Length;    //This is what we learned at school!

The question: How can an array implement IList<T> (especially the int Count { get; } property from IList<T>) without allowing it to be used on the base class?

Edit
Report

1 Answer

13

Because an Array doesn't support all of the features of an IList (Add/Remove/etc), IList.Count (and several other methods) are all implemented privately (explicitly). You can see this in disassembly:

int ICollection.Count

If you really wanted to use Count, you could do

((IList)myArray).Count
answered 2012-09-17T14:24:08.087

Your Answer