serhio
serhio

Reputation: 28586

Should I dispose GDI+ object before its creation?

Should I dispose GDI+ object before its creation?

Is recommended to always Dispose GDI+ object after using it.

by e.g.

Pen p = new Pen(Color.Green);
// use 'p'
p.Dispose();

now, if I have this situation:

Pen p = new Pen(Color.Green);
// use green 'p'

p = new Pen(Color.Red); // Should I Dispose my 'p' first?
// use red 'p'

p.Dispose();

EDIT A:

Using 'USING' is not possible every time.

private Pen p;

public RefreshPen(style)
{
    // p.Dispose(); +-
    p = new Pen(style.Color);
    // etc.
}

EDIT B:

Will this be OK?

using (Pen p = new Pen(Color.Green))
{
    // use green 'p'

    p = new Pen(Color.Red); // Should I Dispose my 'p' first?
    // use red 'p'

    p = new Pen(Color.Blue); // Should I Dispose my 'p' first?
    // use blue 'p'
}

Upvotes: 1

Views: 171

Answers (3)

Jacob G
Jacob G

Reputation: 3665

Can't you just change the properties of the object?

Pen p = new Pen(Color.Green);
//use it here.
p.Color = Color.Red;
//use it some more.
p.Dispose();

Upvotes: 1

dsolimano
dsolimano

Reputation: 8986

Yes. You are creating a new object and assigning it to p, which means you should dispose the old object.

I might code it like so:

using(Pen p = new Pen(Color.Green))
{
    //do some stuff
}

using(Pen q = new Pen(Color.Red))
{
    //do some other stuff
}

This prevents you from forgetting to dispose the pen, or using a disposed object.

Upvotes: 1

Dan Byström
Dan Byström

Reputation: 9244

Yes, you should. (Also note that the using statement is a tremendous help here. I very rarely call .Dispose explicitly. using takes care of that.)

Upvotes: 3

Related Questions