Fields should be disposed
- 2 minutes to read
CodeRush Classic shows the Fields should be disposed code issue if a class implementing IDisposable contains undisposed IDisposable fields.
#Fix
Add the code that disposes IDisposable fields to the Dispose method of the current class.
#Purpose
Highlights the name of the IDisposable class containing undisposed IDisposable fields, because it often denotes incomplete code.
#Example
class FormDrawer: IDisposable
{
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);
}
public void Dispose()
{
GC.SuppressFinalize(this);
}
}
Fix:
class FormDrawer: IDisposable
{
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);
}
public void Dispose()
{
if (_CurrentGraphics != null)
{
_CurrentGraphics.Dispose();
_CurrentGraphics = null;
}
if (_DefaultPen != null)
{
_DefaultPen.Dispose();
_DefaultPen = null;
}
GC.SuppressFinalize(this);
}
}