Question

Say I have a class that implements IEnumerable<T>. It currently uses the yield keyword in the GetEnumerator() method. But now I need to do a bit more, for example I would like to clean up after myself. To do this, unless I have overlooked anything, I need to implement the IEnumerator<T> interface. But where would you say I should do that?

Should the class itself implement it and GetEnumerator() return this? Or would it be better to hide it in a private class? Or should it maybe just be an entirely different class? What are some common practices to this?

Was it helpful?

Solution

If all you need to do is clean up some resources when the enumerator is disposed of, like at the end of a foreach loop, then you can do that with what you have, just add a try/finally block to your iterator method.

Like this:

public IEnumerator<T> GetEnumerator()
{
    try
    {
        // your iterator code here
    }
    finally
    {
        // cleanup code here
    }
}

That's all there is to it.

OTHER TIPS

I would go with a class for the IEnumerator<T>. This will need to store state (current position) that is not part of the collection, but rather part of the process of enumerating.

You may not need to write class for this at all. An iterator method can return IEnumerable<T>, so if your class only needs to implement IEnumerable<T> and nothing else, just write an iterator method for the whole thing.

If not, and you have to stick with an outer class that implements IEnumerable<T> by having an iterator method to do GetEnumerator, then you don't have to do anything very difficult to clean up after iteration.

IEnumerator<T> derives from IDisposable. An iterator method implements Dispose by executing finally blocks or any code after the last yield return.

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