Blog Archive

Tuesday, October 17

Enumerate Using

If you ever need to enumerate a collection of IDisposable items, and you find the following code snippet ugly:

foreach (SomeDisposableClass item in collectionOfDisposableItems)
{
   using (item)
   {
      // do stuff
   }
}

You may find the following method useful:

public static IEnumerable<T> EnumerateUsing<T>(IEnumerable<T> disposableItems)
   where T : IDisposable
{
   foreach (T item in disposableItems)
      using (item)
         yield return item;
}

Calling code looks like:

foreach (SomeDisposableClass item in EnumerateUsing(collectionOfDisposableItems))
{
   // do stuff
}

And yes, Dispose() does get called appropriately after you're finished "doing stuff".

1 comment:

Anonymous said...
This comment has been removed by a blog administrator.