I’ve got an error in my build which says:
Error 12 Cannot implicitly convert type ‘System.Collections.Generic.IEnumerator< BaseClass>’ to ‘System.Collections.Generic.IEnumerator< IParentClass>’. An explicit conversion exists (are you missing a cast?)
Is it wrong to simply cast it away?
This is my code:
public Dictionary<Int32, BaseClass> Map { get; private set; } public IEnumerator<BaseClass> GetEnumerator() { return this.Map.Values.GetEnumerator(); } public IEnumerator<IParentClass> IEnumerable<IParentClass>.GetEnumerator() { return this.GetEnumerator(); // ERROR! }
My question is, can I just change this line:
return this.GetEnumerator();
to:
return (IEnumerator<IParentClass>)this.GetEnumerator();
(without any bad side effects)?
Accepted Answer:
I’ve changed the function to the following (after reading Jon Skeet’s post):
IEnumerator<IParentClass> IEnumerable<IParentClass>.GetEnumerator() { return this.Map.Values.Cast<IParentClass>().GetEnumerator(); }
No you can’t, because generics aren’t covariant in C# at the moment. .NET itself has some support (for delegates and interfaces) but it’s not really used yet.
If you were returning
IEnumerable<BaseClass>instead ofIEnumerator<BaseClass>(and assuming .NEt 3.5) you could useEnumerable.Cast– but you’ll currently need to write your own extension method, e.g.Alternatively in your case you could use Cast earlier: