2

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)

guanabara
  • 590
  • 1
  • 9
  • 22
  • 6
    The compiler/jitter should optimize it for you, but since Pen is a win32 unmanaged resource I'd suggest 1 instance with a `using` clause around it. – asawyer Jan 17 '13 at 16:18

2 Answers2

4

If I were you

using (var green = new Pen(Color,size)
{
    foreach(line to be drawn)
    {
        graphics.DrawLine(green, x1, y1, x2, y2);
    }
}
Mehmet Ataş
  • 11,081
  • 6
  • 51
  • 78
  • This seems a good option. According to msdn the `using` statement "The using statement obtains one or more resources, executes a statement, and then disposes of the resource." Thanks. – guanabara Jan 17 '13 at 16:43
2

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();
Community
  • 1
  • 1
Leo Chapiro
  • 13,678
  • 8
  • 61
  • 92