Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automatically dispose objects inside List?

Tags:

c#

dispose

I have a class with resources which I need to dispose:

class Desert: IDisposable
{
    private object resource; // handle to a resource

    public Desert(string n)
    {
        // Create resource here
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (resource != null) resource.Dispose();
        }
    }
}

I wonder if there is any way to automatically ask framework to call Dispose on each element, whenever the List object is going to be destroyed, just like I would have destructor. Currently I am looping through the list and calling Dispose:

// On form open
List<Desert> desertList = new List<Desert>();
for(int i = 0; i < 10; i++)
{
    desertList.Add(new Desert("Desert" + i));
}


// On form closing
for (int i = 0; i < 10; i++)
{
    desertList[i].Dispose();
}

Is it the only way to dispose objects inside List?

like image 693
Pablo Avatar asked Sep 07 '17 16:09

Pablo


1 Answers

You could extend the List type itself:

public class AutoDisposeList<T> : List<T>, IDisposable where T : IDisposable
{
    public void Dispose()
    {
        foreach (var obj in this)
        {
            obj.Dispose();
        }
    }
}

using (var myList = new AutoDisposeList<Desert>())
{

}

If you need more than that, you could look at Finalizers. These aren't quite destructors - they are methods that run JUST before an object is Garbage Collected. It's very easy to go wrong with these though, my vote is for a using statement.

see: https://msdn.microsoft.com/en-us/library/b1yfkh5e(v=vs.100).aspx

like image 85
Edwin Jones Avatar answered Oct 21 '22 00:10

Edwin Jones