Question

I have a form in which i draw some lines using the Pen object.

I'm wondering if i should use one shared object Pen, or one object Pen per line drawn.

Is is better to use: (one object shared by all lines)

Pen green;
green = new Pen(Color,size);
foreach(line to be drawn)
   graphics.DrawLine(green, x1, y1, x2, y2);

Or the following: (each line is an object)

foreach(line to be drawn)
   Pen green = new Pen(Color.Green, 3);
   graphics.DrawLine(green, x1, y1, x2, y2);
   green.Dispose();

In fact, both examples do what I want, but i'm wondering what is most recommended in this case.

Note: I'm using C# (WinForms)

Was it helpful?

Solution

If I were you

using (var green = new Pen(Color,size)
{
    foreach(line to be drawn)
    {
        graphics.DrawLine(green, x1, y1, x2, y2);
    }
}

OTHER TIPS

Take a look at this one: What happens if I don't call Dispose on the pen object? It seems to be perfectly explained here ...

To keep it short, this one seems to be better :

Pen green = new Pen(Color,size);

foreach(line to be drawn)
   graphics.DrawLine(green, x1, y1, x2, y2);

green.Dispose();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top