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
usingstatement:This automatically disposes the Pen, even if
DrawEllipsewould throw an exception, and the IDE will enforce thatpen1is only available from within the using block.