I switched the FxCop rule today to point out any non-disposed IDisposables as errors, in a hope that it might help me track down some GDI leaks. Interestingly it pointed me to an instance that I'm not quite sure how to deal with:
public class CustomGoRectangle : GoRectangle
{
public void DoStuff()
{
Pen p = new Pen(Color.Red, 4.0f);
this.Pen = p;
}
public void DoOtherStuff()
{
Pen p = new Pen(Color.Blue, 4.0f);
this.Pen = p;
}
public void Test()
{
this.Pen = Pens.Green;
DoStuff();
DoOtherStuff();
}
}
Quick explanation. GoRectangle is within a 3rd party library and has a Pen property, it isn't IDisposable.
I set my pen in a number of places, like the contrived example above. The problem illustrated here is that calling DoStuff()
I create a new pen, which is never disposed. Now I could call dispose on this.Pen if it's not null before assigning a new value, but then as Test()
illustrates if a System Pen has been set this will just cause further problems. What's the actual pattern for dealing with situations like this?