These two questions almost answer my own question, but not quite. Consider this a follow-up question to these.
- Do I need to consider disposing of any IEnumerable<T> I use?
- Understanding Iterator Blocks and Dispose Method
I understand that a foreach
loop will Dispose
of an enumerator when it's done with it.
My question is this:
If the enumerator in question is actually a c# iterator block (i.e. GetEnumerator()/yield
) of an IEnumerable<T>
class which itself implements IDisposable
, can I be sure that the object itself will be disposed? Or do I need to resort to calling GetEnumerator()/MoveNext()/Current
explicitly inside a using
block?
EDIT: This snippet demonstrates @JonSkeet's answer.
EDIT #2: This snippet, based on @JonSkeet's comments, demonstrates ideal usage. The iterator block is responsible for the lifetime of needed resources, not the enumerable object itself. This way, the enumerable can be enumerated multiple times if need be -- each enumerable has its own resource to work with.