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?