Code Snippets for the Dispose Pattern
Join the DZone community and get the full member experience.
Join For FreeI thougth I’d just share a couple of Visual Studio C# code snippets to implement disposable classes, based on the well known .NET dispose pattern.
You can download it from here or simply copy and past it from the listing below. Feel free to rename the shortcut to whatever you like
public class $ClassName$: IDisposable { private bool _disposed = false; //Implement IDisposable. public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { // Free other state (managed objects). } // Free your own state (unmanaged objects). // Set large fields to null. _disposed = true; } } // Use C# destructor syntax for finalization code. ~$ClassName$() { // Simply call Dispose(false). Dispose(false); } }
public class $DerivedClassName$: $BaseClassName$ { private bool _disposed = false; protected override void Dispose(bool disposing) { if (!_disposed) { if (disposing) { // Release managed resources. } // Release unmanaged resources. // Set large fields to null. // Call Dispose on your base class. _disposed = true; } base.Dispose(disposing); } // The derived class does not have a Finalize method // or a Dispose method without parameters because it inherits // them from the base class. }
Published at DZone with permission of Stefano Ricciardi, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments