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?
If all you need to do is clean up some resources when the enumerator is disposed of, like at the end of a
foreachloop, then you can do that with what you have, just add a try/finally block to your iterator method.Like this:
That’s all there is to it.