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>
?
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 }