Question

I'm getting a frustrating error in my code which does not allow me to implement IEnumerable for a class I have created. Let me post the code, as it always makes more sense and it is very short here...

[Serializable]
internal class GroupNode : IGroupNode, IEnumerable<ISceneNode>
{
    public string Name
    {
        get;
        private set;
    }

    const int NumberOfChildren = 8;
    #region Member variables
    private IList<ISceneNode> children = new List<ISceneNode>(NumberOfChildren);
    #endregion

    public IEnumerator<ISceneNode> GetEnumerator()
    {
        return children.GetEnumerator(); //***
    }
...
}

And the interface:

 public interface IGroupNode : ISceneNode, IEnumerable<ISceneNode>
{
    void AddChild(ISceneNode child);
}

And finally, the error message (it is actually pretty descriptive):

Error   1   'Project.SceneGraphCore.GroupNode' does not implement interface member 'System.Collections.IEnumerable.GetEnumerator()'. 'Project.SceneGraphCore.GroupNode.GetEnumerator()' cannot implement 'System.Collections.IEnumerable.GetEnumerator()' because it does not have the matching return type of 'System.Collections.IEnumerator'.    C:\Users\Ian\documents\visual studio 2012\Projects\ISceneGraph\SceneGraph\GroupNode.cs  11  20  SceneGraph

Just what have I done wrong here? All I did was take my collection class, which is based off of a list, and return the List's GetEnumerator method. But then, in the error message, it is saying I have not implemented IEnumerable... I thought that returning GetEnumerator would be sufficient, but I cannot tell in this case.

Was it helpful?

Solution

IEnumerable<T> inherits from IEnumerable (the non-generic version). Any time you implement the generic method you also need to provide a non-generic counterpart.

If you simply right click the interface in Visual Studio it will automatically stub out the functions for you, but you can manually add it if you prefer.

IEnumerator IEnumerable.GetEnumerator()
{
    return children.GetEnumerator();
}

Just add that to the class in addition to the existing methods.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top