Skip to content

Instantly share code, notes, and snippets.

@mazhar-ansari-ardeh
Created January 14, 2017 07:57
Show Gist options
  • Save mazhar-ansari-ardeh/27103bd9e4015d9d99fd7b57e1ed863f to your computer and use it in GitHub Desktop.
Save mazhar-ansari-ardeh/27103bd9e4015d9d99fd7b57e1ed863f to your computer and use it in GitHub Desktop.
A small sample that demonstrates the implementation of Dispose Pattern in C#.
using System;
class BaseClass : IDisposable
{
// Flag: Has Dispose already been called?
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 manualDisposing)
{
if (disposed)
return;
if (manualDisposing) {
// Free any other managed objects here.
//
}
// Free any unmanaged objects here.
//
disposed = true;
}
~BaseClass()
{
Dispose(false);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment