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?
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.
Besides, the IList interface inherits the GetEnumerator() method from the generic IEnumerable interface.
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.
IList Interface (System.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With