Combining foreach and using

apoorv020 picture apoorv020 · Jun 9, 2010 · Viewed 12.9k times · Source

I'm iterating over a ManageObjectCollection.( which is part of WMI interface).

However the important thing is, the following line of code. :

foreach (ManagementObject result in results)
{
    //code here
}

The point is that ManageObject also implements IDisposable, so I would like to put "result" variable in a using block. Any idea on how to do this, without getting too weird or complex?

Answer

David Neale picture David Neale · Jun 9, 2010
foreach (ManagementObject result in results)
using(result)
{
    //code here
}

It's not normally good practice to assign the variable outside the using block because the resource would be disposed but could stay in scope. It would, however, result in clearer code here because you can nested the using statement against the foreach.

EDIT: As pointed out in another answer, ManagementObjectCollection also implements IDisposable so I have added that into a using block.

No need to place ManagementObjectCollection in a using statement. the foreach will call Dispose() on the enumerator.