Sunil
Sunil

Reputation: 21406

Declare the target object of using statement outside the statement in C#

Question: Is there an advantage to declaring the target object of a using statement within the using statement as in 'Code snippet 1' below?

'Code snippet 2' and 'Code snippet 3' snippets seem valid to me also, but not sure if the first code snippet has some benefits over the other two.

Code snippet 1

 using (TextWriter w = File.CreateText("log.txt")) {
     w.WriteLine("This is line one");
     w.WriteLine("This is line two");
  }

Code snippet 2

 TextWrite w = null;
 using (w = File.CreateText("log.txt")) {
     w.WriteLine("This is line one");
     w.WriteLine("This is line two");
  }

Code snippet 3

 TextWriter w = File.CreateText("log.txt");
 using (w) {
     w.WriteLine("This is line one");
     w.WriteLine("This is line two");
  }

UPDATE 1: It seems that 'Code snippet 3' could end up with resources not being disposed when an exception occurs at the first line when TextWriter object is instantiated. So the first two snippets appear equivalent with respect to disposal of resources, while the third snippet is definitely not advisable to use unless the third snippet has a finally block where the TextWriter object is getting disposed.

UPDATE 2: After getting answer from Peter, I realized that my observation in UPDATE 1 is not correct. The explanation is as follows: if an exception occurs when TextWriter is being instantiated in any of the 3 snippets, then the Dispose method will never get called since there is no TextWriter object to call this method on.

Upvotes: 3

Views: 723

Answers (2)

Peter Duniho
Peter Duniho

Reputation: 70671

Your examples #2 and #3 are equivalent, contrary to your assumption in "UPDATE 1". If an exception occurs in the File.CreateText() method call, no object is returned and assigned to w. So whether you make that assignment before the using statement or as part of it, if the object is successfully created, it will be successfully cleaned up as needed.

That said, example #1 is beneficial for at least two reasons:

  1. As mentioned in the other answer, it reduces the scope of the variable so that it's accessible only within the using statement block. This is useful for the same reason scoping variables is useful in any situation.
  2. The other benefit (and IMHO one of the most important ones) is that the variable declared as part of a using statement is read-only. This ensures that you don't accidently write code that tries to switch the disposable object before it can be cleaned up, i.e. creating an ambiguous situation where only one of the disposable objects is cleaned up by the using statement.

Upvotes: 3

Gjeltema
Gjeltema

Reputation: 4166

The only potential benefits are reduced visibility of the declared variable (since it is only visible in the using block), and readability.

Upvotes: 2

Related Questions