According to the accepted answer to Enumerator disposal when not using using, foreach or manually calling Dispose() enumerators in C# must be disposed when finished with, whether you let foreach
do this automatically, or do it yourself if you prefer to write out the equivalent logic by hand.
I wasn't expecting this; would have thought enumerators would be handled by the garbage collector. I'm guessing it's along the lines of:
Database queries are also enumerable, and those need to be disposed because they could be holding database connections, which are a scarcer resource than memory.
To correctly handle this case, the framework designers decided to just make enumerators implement
IDisposable
, so the contract is they should always be disposed; for in-memory collections like strings, arrays and lists, this will be a no-op, but it makes the overall design simpler than trying to make some kinds of enumerators implement a different interface.
Is this correct, or am I missing something?