TLDR:
- Why Dispose should not be invoked IDisposable members in Finalize() method. (possibly with a null check before) except for performance reasons? (when the members are not shared.)
- How can one make sure that IDisposable members free their resources if they should not be disposed in the finalizer and Dispose method wasn't invoked?
From what I have seen, if a class has a field that is IDisposable, then the class should be IDisposable itself. The suggested pattern is:
class MyClass {
// Some memebers that implement IDisposable interface
Dispose()
{
Dispose(true);
GC.SuppressFinalize();
}
Dispose(bool disposed)
{
if(disposed)
{
// Call Dispose on IDesposable members owned by this object
}
// Free additional unmnanaged resources if needed
}
~MyClass()
{
Dispose(false);
}
}
The explanation is that during Finalize method, you don't know the state of other managed resources, hence you don't call Dispose on them. However, on the other hand, how can I make sure that other IDisposable members release their resources? The usual suggestion when working IDisposable objects is to wrap them in using statement or in C# 8 put using statement in the beginning of the block, however, if I am not wrong it is not an option when implementing a class.