tags:

views:

77

answers:

1

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.

+1  A: 

In general, if the class is IDisposable, you must call the .Dispose method when the object is not needed.

Also, the MSDN library says:

Modifying the Region object returned by the Clip property does not affect subsequent drawing with the Graphics object. To change the clip region, replace the Clip property value with a new Region object.

Which means, you MUST dispose oldRgn.

Kerido
I've read the MSDN paragraph four times now, but I still don't see the connection. The same could be said about `Brushes.Red`; The getter returns a disposable object; modifying the object does not affect subsequent drawing. But does that mean I have to dispose `Brushes.Red` every time I invoke the getter?
nikie
Because `Brushes.Red` is a static property, chances are that you won't need to dispose the object. Otherwise, why would the property be static? It is done to save a frequently accessed object for global access and resource reusing. That's the difference between this and your initial question. However, it always makes sense to use Reflector in case of any uncertainty.
Kerido
So essentially, there's no rule - you always have to look at the source to find out if you have to dispose the result of a property getter. And bet on the GC in unclear cases. I feared so, but thanks for your answer anyway.
nikie