Articles → .NET DESIGN PATTERN → Dispose Pattern In C#
Dispose Pattern In C#
Purpose
Implementing Idisposable Interface
public class DisposePatternDemo : IDisposable
{
bool disposed = false;
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
// allow derived classes to override the disposal behavior if needed.
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
// Free any other managed objects here.
}
disposed = true;
}
}
Using Keywords To Initialize The Class
using (DisposePatternDemo demo = new DisposePatternDemo())
{
}