Many GDI+ classes implement IDisposable, but I’m not sure when I should call Dispose. It’s clear for instances I create with new or static methods like Graphics.CreateGraphics. But what about objects that are returned by property getters? I often write code like this:
var oldRgn = g.Clip;
using (var rectRegion = new Region(rectangle))
{
g.Clip = rectRegion;
// draw something
}
g.Clip = oldRgn;
Am I supposed to dispose oldRgn after that? My memory profiler tells me there are undisposed instances if I don’t. And looking at the implementation in reflector at least confirms that the getter apparently creates a new instance every time it’s invoked:
// Graphics.Clip code from Reflector:
public Region get_Clip()
{
Region wrapper = new Region();
int status = SafeNativeMethods.Gdip.GdipGetClip(new HandleRef(this, this.NativeGraphics), new HandleRef(wrapper, wrapper.nativeRegion));
if (status != 0)
{
throw SafeNativeMethods.Gdip.StatusException(status);
}
return wrapper;
}
I couldn’t find anything about that in the MSDN, and the samples in the documentation never seem to dispose anything.
In general, if the class is
IDisposable, you must call the.Disposemethod when the object is not needed.Also, the MSDN library says:
Which means, you MUST dispose
oldRgn.