Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does Queue<T> actually implement

Tags:

c#

.net

c#-4.0

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?

like image 845
Bort Avatar asked Oct 10 '12 19:10

Bort


3 Answers

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.

like image 120
Jon Skeet Avatar answered Sep 22 '22 05:09

Jon Skeet


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

like image 45
Dennis Traub Avatar answered Sep 21 '22 05:09

Dennis Traub


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.

like image 38
D Stanley Avatar answered Sep 22 '22 05:09

D Stanley