Reputation: 6173
I'm writing a simple collection class that implements ICollection<T>
. Everything basically works except if I add a IEnumerator<T> GetEnumerator()
method it complains I don't have an IEnumerator GetEnumerator()
method. And vice versa. I'm not allowed to have both since they differ only in return type, so I'm really quite confused as to what the compiler wants from me.
Here are the errors precisely as they are given to me:
error CS0738:
MyClass<T>' does not implement interface member
System.Collections.Generic.IEnumerable.GetEnumerator()' and the best implementing candidateMyClass<T>.GetEnumerator()' return type
System.Collections.IEnumerator' does not match interface member return type `System.Collections.Generic.IEnumerator'
OR, alternatively I can have:
error CS0738:
MyClass<T>' does not implement interface member
System.Collections.IEnumerable.GetEnumerator()' and the best implementing candidateMyClass<T>.GetEnumerator()' return type
System.Collections.Generic.IEnumerator' does not match interface member return type `System.Collections.IEnumerator'
Upvotes: 2
Views: 2189
Reputation: 65049
Implement them explicitly:
IEnumerator IEnumerable.GetEnumerator() {
}
IEnumerator<T> IEnumerable<T>.GetEnumerator() {
}
// etc.
Explicit interface implementation is how this is achieved. Read about it on MSDN: http://msdn.microsoft.com/en-us/library/aa288461(v=vs.71).aspx
Upvotes: 6
Reputation: 125610
Use explicit interface implementation. That's exactly how List<T>
implements both IEnumerable
and IEnumerable<T>
, pointing to third GetEnumerator
method:
IEnumerator IEnumerable.GetEnumerator()
{
return new List<T>.Enumerator(this);
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return new List<T>.Enumerator(this);
}
public List<T>.Enumerator GetEnumerator()
{
return new List<T>.Enumerator(this);
}
With that kind of declaration you can have couple methods with the same name - as long as they implement some interface method.
Upvotes: 3
Reputation: 4215
ICollection extends IEnumerable. Thus you don't want to do IEnumerable on your class
http://msdn.microsoft.com/en-us/library/92t2ye13.aspx
Upvotes: -3