Question

I am trying to create pens for use in my windows form and I am having issues with the code working properly. The pens are not painting as specified. The code snippets in question are below.

If I create the pens as follows

System.Drawing.Pen aPen = new Pen(Color.Firebrick, 5);
aPen.DashStyle = DashStyle.Solid;

System.Drawing.Pen bPen = new Pen(Color.Firebrick, 1);
bPen.DashStyle = DashStyle.Dot;

everything works properly. However, if I create the pens as follows

System.Drawing.Pen aPen = new Pen(Color.Firebrick, 5);
aPen.DashStyle = DashStyle.Solid;

System.Drawing.Pen bPen = aPen;
bPen.DashStyle = DashStyle.Dot;
bPen.Width = 1;

I end up with both pens having the same color, Firebrick, but both have the dot dash style and both are 1px in width which is not what was specified. Can anyone please explain what is wrong with the code that does not work? Thank you. Clearly there is something I am failing to understand about pens.

Was it helpful?

Solution

The reason of the misbehavior is in the line

  System.Drawing.Pen bPen = aPen; 

This code does't create a new Pen instance, instead it declares a new reference to the existing one which is aPen, Since then there's one instance of Pen class and two references to it: aPen and bPen.

P.S. Pen is IDisposable so do not forget to dispose it in order to prevent resource leak (hPen in your case):

 using (System.Drawing.Pen aPen = new Pen(Color.Firebrick, 5)) {
   aPen.DashStyle = DashStyle.Solid;
   // Paint with aPen here
   ...
 }

 using (System.Drawing.Pen bPen = new Pen(Color.Firebrick, 1)) {
   bPen.DashStyle = DashStyle.Dot;
   // Paint with bPen here
   ...
 }

OTHER TIPS

aPen and bPen are merely alias for same thing. Pen is a reference type and when you equate, it just creates a new name for same instance.

As you have already got an answer, its good. But just FYI, if incase you want same color of a previous pen, then you can write following code:

Pen2.Color = Pen1.Color;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top