How do I check if my object is properly disposed?

.net, dispose, memory-management, visual-studio

Solution

Don't think it is possible; the best you can do is to get a profiler (such as ants profiler) and measure it. If you find that you are leaking memory excessively ( via the profiler), then there is something wrong.

Other than using profiler, I am not sure of any automatic techniques that help you identify undisposed resources.

Problem

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?

Original source