Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

202
Views
using statement for multiple assignments to the variable

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!