Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are .NET object Pen objects disposed if you don't explicitly call Dispose on them?

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?

like image 552
Peter Gillespie Avatar asked Dec 22 '22 02:12

Peter Gillespie


2 Answers

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.

like image 83
C.Evenhuis Avatar answered Dec 24 '22 01:12

C.Evenhuis


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.

like image 42
ken2k Avatar answered Dec 24 '22 02:12

ken2k