foreach(var someDisposableObject in listOfDisposableObjects)
{
//some code
someDisposableObject.Dispose(); //current code contains something like this.
}
Is there safe way, like a using clause to use in this scenario?
For my second iteration (before getting responses) I changed the code to
foreach(var someDisposableObject in listOfDisposableObjects)
{
try
{
//some code
}
finally
{
someDisposableObject.Dispose(); //current code contains something like this.
}
}
though
foreach(var someDisposableObject in listOfDisposableObjects)
{
using( someDisposableObject )
{
//some code
}
}
is much more tidy and most likely safer.
I think this may be your best bet:
EDITED TO ADD:
If you absolutely have to dispose of every object no matter what, then you can do this: