Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle disposable objects we don't have a reference to?

If you have a brush and pen as in:

Brush b = new SolidBrush(color);
Pen p = new Pen(b);

and dispose them like so:

b.Dispose();
p.Dispose();

How would you dispose it if it was:

Pen p = CreatePenFromColor(color) which would create the brush and pen for you? I can't dispose the brush inside this method, right?

Is this a method not to be used with disposable objects?

EDIT: What I mean is, how do you dispose the BRUSH?

like image 662
Joan Venge Avatar asked Oct 08 '09 18:10

Joan Venge


1 Answers

It is the job of the CreatePenFromColor method to dispose of the Brush instance. It's not obvious at a glance but if you dig into the implementation of the Pen class you will see that it does not hold onto the passed in Brush instance. Instead it just uses it to calculate a few values. So there's no reason for the Brush instance to live beyond the call to CreatePenFromColor and the method should be disposing of the instance.

like image 157
JaredPar Avatar answered Sep 27 '22 16:09

JaredPar