Question

I want to understand this topic and not just be able to throw down the syntax. I have a collection class called IGroupNode, which can take in a maximum of 8 children ISceneNodes.

internal class GroupNode : IGroupNode
{
    public string Name
    {
        get;
        private set;
    }

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

    public IEnumerable<ISceneNode> GetEnumerator()
    {
        //?
    }

As you can probably tell, it is a very simple collection class based off of a list. How can I make the implementation of IEnumerable here simply return the internal container’s enumerator? I am not sure how to do this in this very easy case.

Now I am running into trouble with this problem:

'Weber.SceneGraphCore.GroupNode' does not implement interface member 'System.Collections.IEnumerable.GetEnumerator()'. 'Weber.SceneGraphCore.GroupNode.GetEnumerator()' cannot implement 'System.Collections.IEnumerable.GetEnumerator()' because it does not have the matching return type of 'System.Collections.IEnumerator'.
Was it helpful?

Solution

You can simply return children.GetEnumerator() in this case. (By the way your GroupNode object should implement IEnumerable and your GetEnumerator method should have the correct return type.)

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

In more general cases though you can iterate over something and call yield return for each element.

OTHER TIPS

Since IList already implements IEnumerable<>, you can just return children.GetEnumerator() in your GetEnumerator() method.

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