idisposable

How does one Dispose an object that is set in foreach?


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.


Solution

  • I think this may be your best bet:

    try
    {
        foreach(var someDisposableObject in listOfDisposableObjects) 
        { 
            //some code 
        } 
    }
    finally
    {
        foreach(var someDisposableObject in listOfDisposableObjects) 
        { 
            someDisposableObject.Dispose();
        } 
    }
    

    EDITED TO ADD:

    If you absolutely have to dispose of every object no matter what, then you can do this:

        private static void DoStuff(IEnumerable<IDisposable> listOfDisposableObjects)
        {
            using (var enumerator = listOfDisposableObjects.GetEnumerator())
            {
                if (enumerator.MoveNext())
                    DoStuffCore(enumerator);
            }
        }
    
        private static void DoStuffCore(IEnumerator<IDisposable> enumerator)
        {
            using (var someDisposableObject = enumerator.Current)
            {
                if (enumerator.MoveNext())
                    DoStuffCore(enumerator);
    
                // Do stuff with someDisposableObject                
            }
        }