Spot the bug #2 (Code)

Yesterday we stumbled some odd behavior. Totally logical and well defined, but still odd.

I reduced the classes to it’s essentials. Finder is a base class among other things assuring it’s implementor can rely on being called only once per instance.

The particular implementation uses member variables to detect circles in a tree.

Can you spot the problem? Can you tell me how to solve it?

(Update 12.01.2011: While anonymizing I had introduced another bug. Fixed now.)

public abstract class Finder
{
    private bool _used;
    public IEnumerable<int> GetIds()
    {
        if (_used)
            throw new NotSupportedException("Please do not use twice!");

        _used = true;

        return getIds();
    }

    protected abstract IEnumerable<int> getIds();
}

public class FlatHierarchyIdsFinder : Finder
{
    List<int> _visited = new List<int>();
    protected override IEnumerable<int> getIds()
    {
        if (_visited.Contains(1))
            throw new ApplicationException("Cycle detected!");

        _visited.Add(1);
        yield return 1;
    }
}

It might help you to read this post: Behind the scenes of the C# yield-keyword

Advertisements