If an exception is thrown from IEnumerator<T>.MoveNext() or .Current, must it be still be disposed?
-
08-10-2019 - |
문제
Intuitively I think yes, but I'm not sure if there's some convention I don't know about.
해결책
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
다른 팁
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.