You could do the following.
foreach (ManagementObject result in results)
{
using (result)
{
// Your code goes here.
}
}
The neat thing about C# is how different language constructs can share scoped code blocks. That means you could do the following to eliminate the nesting.
foreach (ManagementObject result in results) using (result)
{
// Your code goes here.
}
It is also useful to know that the foreach
construct will call Dispose
on the target IEnumerator
as well. The code above would be equivalent to.
IEnumerator enumerator = results.GetEnumerator()
try
{
while (enumerator.MoveNext())
{
ManagementObject result = (ManagementObject)enumerator.Current;
IDisposable disposable = (IDisposable)result;
try
{
// Your code goes here.
}
finally
{
disposable.Dispose();
}
}
}
finally
{
IDisposable disposable = enumerator as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
}