Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

c#

list

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?

like image 638
Gerrit Avatar asked Sep 17 '12 14:09

Gerrit


People also ask

Does array implement IList?

Definition of IList interface is "Represents a non-generic collection of objects that can be individually accessed by index.". Array completely satisfies this definition, so must implement the interface.

What inherits from IList?

Besides, the IList interface inherits the GetEnumerator() method from the generic IEnumerable interface.

What is IList C#?

In C# IList interface is an interface that belongs to the collection module where we can access each element by index. Or we can say that it is a collection of objects that are used to access each element individually with the help of an index. It is of both generic and non-generic types.

Which interface represents a collection of objects that can be individually access by index?

IList Interface (System.


1 Answers

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:

interface I {     void M(); }  class C : I {     public int P { get; set; }     void I.M() { Console.WriteLine("M!"); } } 

Then you can use these types like this:

C obj = new C(); obj.P = 3; ((I)obj).M(); 

But this won't compile:

obj.M(); 

As JeffN825 notes, one reason for implementing the interface members explicity is that they're not supported by the type. For example, Add throws 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 reason Count is implemented explicitly; the corresponding public member is Length. Finally, some members are implemented implicitly, namely, the indexer. Both of these lines work (assuming arr is an array of int):

arr[0] = 8; ((IList<int>)arr)[0] = 8; 
like image 194
phoog Avatar answered Sep 21 '22 21:09

phoog