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?
This is known as an explicit interface member implementation. The interface member is not exposed as a public member of the type, but it is available by casting the reference to the interface type.
This can be done in C# like this:
Then you can use these types like this:
But this won’t compile:
As JeffN825 notes, one reason for implementing the interface members explicity is that they’re not supported by the type. For example,
Addthrows an exception (relevant discussion). Another reason for implementing a member explicity is that it duplicates another public member with a different name. That’s the reasonCountis implemented explicitly; the corresponding public member isLength.Finally, some members are implemented implicitly, namely, the indexer. Both of these lines work (assumingarris an array ofint):