I wonder if there a "trick" that permits to know if the used objects in a portion o code has been properly(entirely) disposed, or, in other words don't creates memory leaks.
Let's say I have a container of GDI objects (or other that I need to explicitly dispose)
public class SuperPen
{
Pen _flatPen, _2DPen, _3DPen;
public SuperPen()
{
_flatPen = (Pen)Pens.Black.Clone();
_2DPen = (Pen)Pens.Black.Clone();
_3DPen = (Pen)Pens.Black.Clone();
}
}
Now, as I need to Dispose the GDI objects I do:
public class SuperPen : IDisposable
{
Pen _flatPen, _2DPen, _3DPen;
public SuperPen()
{
_flatPen = (Pen)Pens.Black.Clone();
_2DPen = (Pen)Pens.Black.Clone();
_3DPen = (Pen)Pens.Black.Clone();
}
public void Dispose()
{
if (_flatPen != null) { _flatPen.Dispose(); _flatPen = null; }
// HERE a copy paste 'forget', should be _2DPen instead
if (_flatPen != null) { _flatPen.Dispose(); _flatPen = null; }
if (_3DPen != null) { _3DPen.Dispose(); _3DPen = null; }
}
}
Situation like this can happen if you add a new "disposable" object and forget to dispose it etc. How can I detect my error, I mean, check if my SuperPen was properly disposed?