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:
public class Queue<T> : IEnumerable<T>, ICollection, IEnumerable
So it implements the generic IEnumerable<T>
interface, but the non-generic ICollection
interface.
Don't let the similarity of the names fool you - ICollection
and ICollection<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 in Queue<T>
, but equally they wanted to implement ICollection
to allow folks to upgrade from the non-generic Queue
class painlessly.
EDIT: As noted in Dennis's answer, ICollection.CopyTo
is implemented explicitly in Queue<T>
. This means that you can only get to that signature via an expression of type ICollection
. For example:
Queue<string> queue = new Queue<string>();
Array array = new Button[10];
queue.CopyTo(array, 0, queue.Count); // Compilation failure...
ICollection collection = (ICollection) queue;
collection.CopyTo(array, 0, queue.Count); // Compiles, but will go bang
The method taking a strongly typed array would be valid to implement ICollection<T>.CopyTo
, but the Add
and Remove
methods of ICollection<T>
aren't present - instead, you're meant to Enqueue
and Dequeue
values.
Queue has its own CopyTo() implementation and it explicitly implements ICollection.CopyTo(), according to the MSDN documentation: http://msdn.microsoft.com/en-us/library/7977ey2c.aspx
Because ICollection<T>
contains a Remove
method that removes an item from any place in the collection. This is not applicable to a Queue since you can only remove the top item without rebuilding the entire queue.
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