Class should implement IDisposable
- 2 minutes to read
CodeRush Classic shows the Class should implement IDisposable code issue if a class containing IDisposable fields does not implement IDisposable.
#Fix
Make the current class implement IDisposable.
#Purpose
Highlights classes containing IDisposable fields if the class does not implement IDisposable, because it often denotes incomplete code.
#Example
class FormDrawer
{
private Graphics _CurrentGraphics;
private Pen _DefaultPen;
public FormDrawer(Form operatedForm)
{
_CurrentGraphics = operatedForm.CreateGraphics();
_DefaultPen = new Pen(Color.Black);
}
public void DrawCircle(int centerX, int centerY, int radius)
{
_CurrentGraphics.DrawEllipse(_DefaultPen, centerX - radius, centerY - radius, radius * 2, radius * 2);
}
public void DrawCircle(int centerX, int centerY, int radius, Pen pen)
{
_CurrentGraphics.DrawEllipse(pen, centerX - radius, centerY - radius, radius * 2, radius * 2);
}
}
Fix:
class FormDrawer: IDisposable
{
private Graphics _CurrentGraphics;
private Pen _DefaultPen;
private bool _Disposed;
public FormDrawer(Form operatedForm)
{
_CurrentGraphics = operatedForm.CreateGraphics();
_DefaultPen = new Pen(Color.Black);
}
public void DrawCircle(int centerX, int centerY, int radius)
{
_CurrentGraphics.DrawEllipse(_DefaultPen, centerX - radius, centerY - radius, radius * 2, radius * 2);
}
public void DrawCircle(int centerX, int centerY, int radius, Pen pen)
{
_CurrentGraphics.DrawEllipse(pen, centerX - radius, centerY - radius, radius * 2, radius * 2);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_Disposed)
{
if (disposing)
{
if (_CurrentGraphics != null)
{
_CurrentGraphics.Dispose();
_CurrentGraphics = null;
}
if (_DefaultPen != null)
{
_DefaultPen.Dispose();
_DefaultPen = null;
}
}
}
_Disposed = true;
}
~FormDrawer()
{
this.Dispose(false);
}
}