Stack<T> implements ICollection, but has methods from ICollection<T>
Asked Answered
J

2

6

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

Janitress answered 14/5, 2012 at 19:26 Comment(9)
The methods are implemented explicitly. Explicitly implemented methods are not public and therefore would not show up in the metadata (which only lists public properties).Directorate
You might try .NET Reflector to see the actual complete source code of Stack<T>, including private methods.Cowles
@JeffMercado Wow... I can't believe it was that easy. I always wondered what "Explicitly Implement suchnsuch" meant. Thanks.Janitress
Posted the .NET 4.0 implementation of Stack<T> if you want to take a look. pastebin.com/p2k4URtUActuary
@SPFiredrake, how did you get that?!Devaughn
@JeffMercado you should probably post that as an answer and briefly explain how to explicitly implement an interface so you can get the credit.Outdoor
@JeffMercado - your answer, which is good, is more useful as an answer than a comment. Strangely, I've seen more and more people use comments to answer questions lately. Go figure.Cordovan
@C.E: I'm swamped at work right now and would have otherwise provided a full answer. The best that I could do with the time I have is to throw in a comment. It's hard to force myself to put in a sub-standard answer (by my standards).Directorate
@Devaughn - downloading Framework source from within VS has been around for a while. Take a look at this article: blogs.msdn.com/b/rscc/archive/2010/08/16/…Cordovan
S
3

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
}
Solitary answered 14/5, 2012 at 20:19 Comment(0)
A
0

I guess the method CopyTo(Array array, index) is implemented explicitly. This means, you will only see that method if you see the object as an ICollection:

var collection = (ICollection)stack;
collection.CopyTo(array, 0);
Angulation answered 14/5, 2012 at 20:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.