Si se produce una excepción de IEnumerator .MoveNext () o .Current, ¿debe todavía ser eliminados?
-
08-10-2019 - |
Pregunta
Intuitivamente creo que sí, pero no estoy seguro si hay alguna convención no sé acerca.
Solución
Since we can't know what the implementation is, the only safe answer is "yes".
However, it is very rare to use IEnumerator
directly - foreach
being more common. For the generic IEnumerator<T>
you can use a using statement:
using(var iter = obj.GetEnumerator()) {
...
}
Even without the generic version, you can cheat:
IEnumerator iter = obj.GetEnumerator();
using(iter as IDisposable) {
...
}
Which will dispose iter if it is IDisposable
Otros consejos
No disposable object MUST be disposed, ever.[1]
But they should be. As a using
block uses the finally
clause to dispose and this is executed whether the using
block is exited normally or via an exception, the default is to dispose even in the face of an exception.
[1] I suppose one could have a buggy implementation where a non-managed resource is held and there is no finaliser, but the correct action there is to implement a finaliser.