Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm 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 would require it to implement ICollection's CopyTo(Array array, index) method, but instead, it is shown as having ICollection<T>'s CopyTo(T[] array, index) method. Can someone explain why this is the case?

I'm trying to create a collection that mimics Stack<T> pretty heavily. When I implement ICollection as stack does, it requires me to use the CopyTo(Array array, index) method, but what I really want is to use the CopyTo(T[] array, index) method, like Stack<T> does. Is there a way to achieve this without implementing ICollection<T>?

like image 399
Thick_propheT Avatar asked May 14 '12 19:05

Thick_propheT


People also ask

Which interface does ICollection T inherit from?

The ICollection<T> interface is the base interface for classes in the System. Collections. Generic namespace. The ICollection<T> interface extends IEnumerable<T>; IDictionary<TKey,TValue> and IList<T> are more specialized interfaces that extend ICollection<T>.

Does ICollection implement IEnumerable?

ICollection implements IEnumerable and adds few additional properties the most use of which is Count. The generic version of ICollection implements the Add() and Remove() methods.

Should I use IList or IEnumerable?

You use IEnumerable when you want to loop through the items in a collection. IList is when you want to add, remove, and access the list contents out of order. Save this answer.

What is the use of ICollection in C#?

The ICollection interface in C# defines the size, enumerators, and synchronization methods for all nongeneric collections. It is the base interface for classes in the System. Collections namespace.


1 Answers

As others have written, you can use 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
}
like image 71
Jeppe Stig Nielsen Avatar answered Sep 28 '22 05:09

Jeppe Stig Nielsen