Using IDisposable may not be enough, because it relies on a user who wants to call Dispose or use using , etc.
For a complete solution, combine IDisposable and a finalizer. Like this:
Edit: Some corrections have been made to the Dispose method based on the SpeksETC comment.
class MyClass : IDisposable { ~MyClass() { Dispose(false); } public void Dispose() { GC.SupressFinalize(); Dispose(true); } protected virtual void Dispose(bool disposing) { if (!disposing) {
This ensures that internal resources are always cleared, even if the user forgot to call Dispose , but at the same time allows the user to quickly clear the resources.
An if required inside the Dispose implementation, because if this class terminates, you can not call Dispose for your members, because they have already been GC'ed already.
source share