C #: where to implement a custom IEnumerator <T>
Let's say I have a class that implements IEnumerable<T>
. He is currently using the keyword yield
in the method GetEnumerator()
. But now I need to do a little more, for example I would like to clear myself. To do this, if I haven't missed anything, I need to implement an interface IEnumerator<T>
. But where would you say that I have to do this?
Does the class itself have to implement it and GetEnumerator()
return this
? Or would it be better to hide it in a private classroom? Or could it just be a completely different class? What are some common practices?
source to share
If all you have to do is clean up some resources when the enumerator is removed, for example at the end of a loop foreach
, then you can do it 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 it takes.
source to share
You may not have to write a class for this. The iterator method can return IEnumerable<T>
, so if your class needs to implement IEnumerable<T>
and nothing else, just write an iterator method for the whole thing.
If not, and you should stick with the outer class that implements IEnumerable<T>
using the iterator method GetEnumerator
, you don't need to do anything very hard to clean up after iteration.
IEnumerator<T>
comes from IDisposable
. The iterator method implements Dispose
by executing blocks finally
or any code after the last one yield return
.
source to share