Created
March 7, 2016 16:54
-
-
Save azborgonovo/c086d14bdab3900843c9 to your computer and use it in GitHub Desktop.
Disposable abstract class in C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Abstraction for an easier Disposable pattern implementation. | |
/// Consumers should override the DisposeManagedObjects and DisposeUnmanagedObjects | |
/// to dispose the desired objects | |
/// </summary> | |
/// <remarks>https://msdn.microsoft.com/pt-br/library/fs2xkftw(v=vs.110).aspx</remarks> | |
public abstract class Disposable : IDisposable | |
{ | |
protected bool disposed = false; | |
// Public implementation of Dispose pattern callable by consumers. | |
public void Dispose() | |
{ | |
Dispose(true); | |
GC.SuppressFinalize(this); | |
} | |
// Protected implementation of Dispose pattern. | |
protected virtual void Dispose(bool disposing) | |
{ | |
if (disposed) | |
return; | |
if (disposing) | |
{ | |
DisposeManagedObjects(); | |
} | |
DisposeUnmanagedObjects(); | |
disposed = true; | |
} | |
/// <summary> | |
/// Free any managed objects | |
/// </summary> | |
protected virtual void DisposeManagedObjects() { } | |
/// <summary> | |
/// Free any unmanaged objects | |
/// </summary> | |
protected virtual void DisposeUnmanagedObjects() { } | |
~Disposable() | |
{ | |
Dispose(false); | |
} | |
} | |
public class MyClass : Disposable | |
{ | |
protected override void DisposeManagedObjects() | |
{ | |
// Free any managed objects here. | |
base.DisposeManagedObjects(); | |
} | |
protected override void DisposeUnmanagedObjects() | |
{ | |
// Free any unmanaged objects here. | |
base.DisposeManagedObjects(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment