Monday, June 16, 2008

IEnumerable with expensive resources

Often IEnumerable types allocate scarce resources in GetEnumerator(). For example, the IEnumerator returned from GetEnumerator may hold a reference to an expensive array of Disposable objects. Such IEnumerator types should implement the IDisposable interface to allow explicit cleanup.
internal class ExpensiveEnumerator: IEnumerator, IDisposable{


public class ExpensiveCollection: IEnumerable{
public IEnumerator GetEnumerator(){
return new ExpensiveEnumerator();


Some languages, for example C# and VB.NET, will call Dispose on enumerators that implement IDisposable when the foreach statement completes.
ExpensiveCollection expensive = new ExpensiveCollection();
foreach(ExpensiveItem in expensiveCollection){

} // Dispose will be called on the IEnumerator when the loop terminates

No comments: