2

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.

4
  • 2
    Using statement is only applicable for object with implement IDisposable interface. If the Pen implement IDisposable, then yes you can use the using statement. Commented Jan 31, 2022 at 10:42
  • 9
    Reassigning the variable defeats the point of using. Are you using an odd variant of C# where you have to pay for additional variables? If not, just have 3 separate ones. Commented Jan 31, 2022 at 10:43
  • 4
    using Pen grayPen = new Pen(Color.Gray); using Pen greenPen = new Pen(Color.Green); etc.? (If you're using an older version of C# than 8 you'll need the traditional style using blocks but the concept is the same: one variable per pen). Commented Jan 31, 2022 at 10:43
  • 1
    You can use 3 separate variables with the same name, with different scopes: using (var pen = new Pen(Color.Gray)) { ... } using (var pen = new Pen(Color.Green)) { ... } Commented Jan 31, 2022 at 10:44

1 Answer 1

5

Well, Pen implements IDisposable since it allocates unmanaged resources (HPEN) and thus in general case using is required. In your current code you have resource leakage:

Pen pen = new Pen(Color.Gray);

// some code which uses gray value

pen = new Pen(Color.Green); // <- from now on Pen(Color.Gray) is leaked

// some code which uses green value
pen = new Pen(Color.Red);  // <- from now on Pen(Color.Green) is leaked
// some code which uses red value

You can either use predefined pens (no using required):

Pen pen = Pens.Gray;

// some code which uses gray value

pen = Pens.Green;

// some code which uses green value

pen = Pens.Red;

// some code which uses red value

Or if you want to create Pens manually, wrap them into using:

using (Pen pen = new Pen(Color.Gray)) {
  // some code which uses gray value
}

using (Pen pen = new Pen(Color.Green) {
  // some code which uses green value
}

using (Pen pen = new Pen(Color.Red)) {
  // some code which uses red value
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.