I have a variable "pen" of type System.Drawing.Pen which is getting assigned multiple times in a particular method. I want to put it within "using" statement. How I can do that?
Pen pen = new Pen(Color.Gray);
// some code which uses gray value
pen = new Pen(Color.Green);
// some code which uses green value
pen = new Pen(Color.Red);
// some code which uses red value
Thanks in advance.
Well,
PenimplementsIDisposablesince it allocates unmanaged resources (HPEN) and thus in general caseusingis required. In your current code you have resource leakage:You can either use predefined pens (no
usingrequired):Or if you want to create
Pens manually, wrap them intousing: