views:

133

answers:

3

Hi there, I have a question about the IEnumerator.GetEnumerator() method.

public class NodeFull
{
    public enum Base : byte {A = 0, C, G, U };
    private int taxID;
    private List<int> children;

    public int TaxID
    {
        get { return taxID; }
        set { taxID = value; }
    }

    public int this[int i]
    {
        get { return children[i]; }
        set { children[i] = value; }
    }

    public IEnumerator GetEnumerator()
    {
        return (children as IEnumerator).GetEnumerator();
    }

    public TaxNodeFull(int taxID)
    {
        this.taxID = taxID;
        this.children = new List<int>(3);
    }
}

When I try to compile, error message says

'System.Collections.IEnumerator' does not contain a definition for 'GetEnumerator' and no extension method 'GetEnumerator' accepting a first argument of type 'System.Collections.IEnumerator' could be found (are you missing a using directive or an assembly reference?)

Is there anything wrong with the code?

Thanks in advance


Thank you guys. I got it.

+8  A: 

It's IEnumerable.GetEnumerator() (or IEnumerable<T>.GetEnumerator()), not IEnumerator.GetEnumerator(). The members on IEnumerator are MoveNext(), Current and Reset() (and Dispose for the generic version). The IEnumerable is "something that can be iterated over" (e.g. a list) and the IEnumerator represents the current state within that iteration - like a database cursor.

It's slightly odd that your class doesn't implement IEnumerable or IEnumerable<T> itself. I'd expect something like this:

class NodeFull : IEnumerable<int>
{
    ... other stuff as normal ...

    public IEnumerator<int> GetEnumerator()
    {
        return children.GetEnumerator();
    }

    // Use explicit interface implementation as there's a naming
    // clash. This is a standard pattern for implementing IEnumerable<T>.
    IEnumerator IEnumerable.GetEnumerator()
    {
        // Defer to generic version
        return GetEnumerator();
    }
}
Jon Skeet
+1  A: 

There is no GetEnumerator() method on the IEnumerator interface. Are you trying to use the IEnumerABLE interface perhaps?

Steve Danner
+2  A: 

children is List<int>, which implements IEnumerable<int> and IEnumerable. The GetEnumerator() method is defined for those interfaces, not for IEnumerator.

children as IEnumerator should result in null.

Anthony Pegram