While attempting to implement my own Queue by wrapping the generic Queue, I noticed that Queue implements ICollection. However, the method signature of ICollection.CopyTo is as follows
void CopyTo(
Array array,
int index)
Whereas the method signature of the generic Queue.CopyTo is
public void CopyTo(
T[] array,
int arrayIndex)
This is the same as the signature of the generic version of ICollection.CopyTo. My confusion comes from the fact that the generic queue doesn’t seem to implement the generic ICollection, but instead implements the standard ICollection. So what exactly is going on here?
As per the documentation:
So it implements the generic
IEnumerable<T>interface, but the non-genericICollectioninterface.Don’t let the similarity of the names fool you –
ICollectionandICollection<T>are entirely separate interfaces, and while something like this (implementing some generic interfaces but only non-generic other interfaces) is unusual, it’s entirely legitimate.I suspect that there were various aspects of
ICollection<T>which the designers really didn’t want to support inQueue<T>, but equally they wanted to implementICollectionto allow folks to upgrade from the non-genericQueueclass painlessly.EDIT: As noted in Dennis’s answer,
ICollection.CopyTois implemented explicitly inQueue<T>. This means that you can only get to that signature via an expression of typeICollection. For example:The method taking a strongly typed array would be valid to implement
ICollection<T>.CopyTo, but theAddandRemovemethods ofICollection<T>aren’t present – instead, you’re meant toEnqueueandDequeuevalues.