views:

33

answers:

2

I am implementing a class that basicaly wraps an array:

public abstract class IndividualBase : IEnumerable<Gene>
{
    private readonly Gene[] genoma;

    ...

    public IEnumerator<Gene> GetEnumerator()
    {
        return genoma.GetEnumerator();
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return genoma.GetEnumerator();
    }
}

The problem is that it's giving me trouble with the first GetEnumerator() -- it tells me that

Cannot implicitly convert type 'System.Collections.IEnumerator' to 'System.Collections.Generic.IEnumerator'. An explicit conversion exists (are you missing a cast?)

Although I understand what the problem is, I have absolutely no idea how to fix it. Anyone?

Thanks

+6  A: 

You could try:

IEnumerable<Gene> typed = genoma;
return typed.GetEnumerator();

Just to make the compiler happy. While arrays implement the generic Enumerable interface, this isn't present on the public GetEnumerator(). With the above we simply cast to the preferred API. This is a trivial cast; no check should happen at runtime (since the compiler and CLI know it is valid).

Marc Gravell
FYI: I like this better than my `genoma.Cast<Gene>().GetEnumerator()` answer. Cast _might_ be smart enough to do this under the hood, but it also might add an extra layer of indirection to cast each item, instead of the entire thing.
Brian Genisio
+1, most efficient answer.
driis
A: 

Your problem is that you are returning an IEnumerable, not an IEnumerble<Gene>

Change it to this:

return genoma.Cast<Gene>().GetEnumerator();

EDIT

Keeping this around for another way to do it, BUT, I prefer Marc's answer better.

Brian Genisio