Stack <T> implements ICollection, but has methods from ICollection <T>

I am trying to create a custom collection based on Stack<T> . When I look at Stack<T> [from metadata] in visual studio, it shows that Stack<T> implements ICollection , which will require it to implement the CopyTo(Array array, index) method, but instead it displays as having ICollection<T> CopyTo(T[] array, index) . Can someone explain why this is so?

I am trying to create a collection that imitates Stack<T> very strongly. When I implement ICollection as a stack, I need to use the CopyTo(Array array, index) method, but I really want to use the CopyTo(T[] array, index) method, for example Stack<T> . Is there a way to achieve this without implementing ICollection<T> ?

+6
source share
2 answers

As others have written, you can use an explicit interface implementation to satisfy your non-generic interface:

 void ICollection.CopyTo(Array array, int arrayIndex) { var arrayOfT = array as T[]; if (arrayOfT == null) throw new InvalidOperationException(); CopyTo(arrayOfT, arrayIndex); // calls your good generic method } 
+3
source

I assume the CopyTo(Array array, index) method is implemented explicitly. This means that you will see this method only if you see the object as an ICollection:

 var collection = (ICollection)stack; collection.CopyTo(array, 0); 
0
source

Source: https://habr.com/ru/post/915718/


All Articles