c# - Why does IEnumerator<T> inherit from IDisposable while the non-generic IEnumerator does not? -
i noticed generic ienumerator<t>
inherits idisposable, non-generic interface ienumerator not. why designed in way?
usually, use foreach statement go through ienumerator<t>
instance. generated code of foreach has try-finally block invokes dispose() in finally.
basically oversight. in c# 1.0, foreach
never called dispose
1. c# 1.2 (introduced in vs2003 - there's no 1.1, bizarrely) foreach
began check in finally
block whether or not iterator implemented idisposable
- had way, because retrospectively making ienumerator
extend idisposable
have broken everyone's implementation of ienumerator
. if they'd worked out it's useful foreach
dispose of iterators in first place, i'm sure ienumerator
have extended idisposable
.
when c# 2.0 , .net 2.0 came out, however, had fresh opportunity - new interface, new inheritance. makes more sense have interface extend idisposable
don't need execution-time check in block, , compiler knows if iterator ienumerator<t>
can emit unconditional call dispose
.
edit: it's incredibly useful dispose
called @ end of iteration (however ends). means iterator can hold on resources - makes feasible to, say, read file line line. iterator blocks generator dispose
implementations make sure finally
blocks relevant "current point of execution" of iterator executed when it's disposed - can write normal code within iterator , clean-up should happen appropriately.
1 looking @ 1.0 spec, specified. haven't yet been able verify earlier statement 1.0 implementation didn't call dispose
.
Comments
Post a Comment