Pen
implements IDisposable
, which means that it should be disposed of as soon as it's not needed anymore. You should not create it directly within the DrwaLine
call (since there's no way to dispose of it). It should not be a class member either, assuming it's only needed for the DrawLine
call.
A better approach would be:
private void Form1_Paint(object sender, PaintEventArgs e)
{
using(Pen pen = new Pen(Color.Black))
{
e.Graphics.DrawLine(tpen, ...);
}
}
That way the pen is disposed of even if an exception occurs.
If all you're setting is the color, you can inline it by using the static Pens.Black
property:
e.Graphics.DrawLine(Pens.Black, ...);
Since the object will be cached by the Pen
class and you don't need to worry about disposing of it.