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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With