While writing a small paint-like application (for myself), I originally had the following code being called in the onClick handler:
g.DrawEllipse((new Pen(pencolour, penSize)), e.X, e.Y, 1, 1);
which I later changed to
Pen pen1 = new Pen(pencolour, penSize);
g.DrawEllipse(pen1, e.X, e.Y, 1, 1);
pen1.Dispose();
My question is: are the two pieces of code equivalent, or does the first one create Pen objects which are never disposed of?
They are disposed when the Garbage Collector runs and determines the object is no longer in use. It is better to dispose of objects yourself, so the resources are freed immediately.
Also consider the use of the using
statement:
using (Pen pen1 = new Pen(pencolour, penSize))
{
g.DrawEllipse(pen1, e.X, e.Y, 1, 1);
}
This automatically disposes the Pen, even if DrawEllipse
would throw an exception, and the IDE will enforce that pen1
is only available from within the using block.
As Pen
implements IDisposable
, it's better to use the using statement to ensure Dispose
is called.
using (Pen pen1 = new Pen(pencolour, penSize))
{
g.DrawEllipse(pen1, e.X, e.Y, 1, 1);
}
If you don't, pen1
will be GC-ed later as it's not used after it goes out of scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With