Declare the target of using an operator outside of an expression in C #

Question . Is there an advantage to declaring the target of a using statement in a using statement, as shown in "code snippet 1" below?

The code snippets and code snippets below 3 also seem useful to me, but not sure if the first code snippet has some advantages over the other two.

Snippet 1

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

      

Snippet 2

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

      

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 looks like "code snippet 3" might end up with resources not being disposed of when an exception is thrown on the first line when the TextWriter is created. Thus, the first two snippets are equivalent in terms of disposing of resources, while the third snippet is definitely inappropriate if there is no finally block in the third snippet where the TextWriter object will be deleted.

UPDATE 2: . After getting a response from Peter, I realized that my observation in UPDATE 1 was wrong. The explanation is as follows: if an exception is thrown when a TextWriter is created in any of the 3 fragments, the Dispose method will never be called because the TextWriter object will not include this method.

+3


source to share


2 answers


Your examples # 2 and # 3 are equivalent, as opposed to your assumption in " UPDATE 1 ". If File.CreateText()

an exception is thrown in the method call , the object is not returned or assigned w

. Therefore, regardless of whether you perform this assignment before the statement using

or as part of it, if the object is successfully created, it will be cleaned up successfully as needed.

However, example # 1 is useful for at least two reasons:



  • As mentioned in another answer, it shrinks the scope of the variable so that it is only available in the statement block using

    . This is useful for the same reason that scope variables are useful in any situation.
  • Another advantage (and IMHO one of the most important) is that a variable declared as part of a statement using

    is read-only. This ensures that you don't accidentally write code that tries to toggle the disposable before it is cleared, i.e. Creating an ambiguous situation where only one of the disposable objects is cleared by the operator using

    .
+2


source


The only potential benefits are reduced visibility of the declared variable (since it is only visible in the block using

) and readability.



+2


source







All Articles