Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What scope does a using statement have without curly braces

Tags:

I inherited the following code:

    using (var dataAccessConnection = da.GetConnection()) //no opening curly brace here     using (var command = new SqlCommand(sql, dataAccessConnection.Connection))     {         command.CommandType = CommandType.Text;         using (var sqlDataReader = command.ExecuteReader(CommandBehavior.CloseConnection))         {             while (sqlDataReader.Read())             {                 rueckgabe.Add(new Myclass                                   {                                       Uid = Guid.NewGuid(),                                       ImportVersionUid = versionUid,                                       MyProperty = Convert.ToInt32(sqlDataReader["MyProperty"])                                         });                    }         }         command.Connection.Close();         dataAccessConnection.Connection.Close();     } 

Looking at the code I expexted an opening curly brace after the using clause.

The code compiles and does what it is expected to do. The application behaves unpredictable. At some time it cant access the Database server.

Does this code make sense? Does dataAccessConnection have the rigth scope?

like image 741
Mathias F Avatar asked Jul 18 '14 07:07

Mathias F


People also ask

What happens in a IF statement where there is no curly braces?

Without curly braces only first statement consider in scope so statement after if condition will get executed even if there is no curly braces. But it is Highly Recommended to use curly braces. Because if the user (or someone else) ever expands the statement it will be required.

When can curly braces be omitted from an if statement?

So we can omit curly braces only there is a single statement under if-else or loop. Here in both of the cases, the Line1 is in the if block but Line2 is not in the if block. So if the condition fails, or it satisfies the Line2 will be executed always.

What is the purpose of curly braces?

Different programming languages have various ways to delineate the start and end points of a programming structure, such as a loop, method or conditional statement. For example, Java and C++ are often referred to as curly brace languages because curly braces are used to define the start and end of a code block.

What programming language uses curly brackets?

Curly braces (also referred to as just "braces" or as "curly brackets") are a major part of the C++ programming language. They are used in several different constructs, outlined below, and this can sometimes be confusing for beginners. An opening curly brace { must always be followed by a closing curly brace } .


2 Answers

Beginning with C# 8.0, the using keyword can be used as an attribute in the variable declarations of disposable objects (Reference). The semantics is as you would expect -- the objects are auto-disposed at the end of the scope.

        public class Disposable : IDisposable         {             string name;              public Disposable(string name)             {                 this.name = name;             }              public void Dispose()             {                 Console.WriteLine(name + " disposed");             }              public void Identify()             {                 Console.WriteLine(name);             }              static void Main(string[] args)             {                 using Disposable d1 = new Disposable("Using 1");                 Disposable d2 = new Disposable("No Using 2");                 using Disposable d3 = new Disposable("Using 3");                 Disposable d4 = new Disposable("No Using 4");                 d1.Identify();                 d2.Identify();                 d3.Identify();                 d4.Identify();             }         } 

Output

 Using 1 No Using 2 Using 3 No Using 4 Using 3 disposed Using 1 disposed 
like image 126
Gopi Reddy Avatar answered Nov 10 '22 19:11

Gopi Reddy


using statements without explicit curly braces apply only to the following statement.

using (Idisp1)     // use it  // it's disposed 

Thus, when chained, they work the same way. The second using here acts as a single statement.

using (Idisp1)     using (Idisp2)     {      } 

Commenter stakx suggested that formatting to make it clear how the compiler reads the using blocks. In reality, these would usually be formatted as the OP encountered:

using (Idisp1) using (Idisp2) {  } 

That is equivalent to this:

using (Idisp1) {     using (Idisp2)     {      } } 

Notice that the first at the top is always the last to dispose. Thus, in all previous examples, Idisp2.Dispose() is called before Idisp1.Dispose(). That isn't relevant in many cases where you would do something like this, but I believe you should always be aware of what your code will do and make the informed decision not to care.

An example of this is when reading a web page:

HttpWebRequest req = ...;  using (var resp = req.GetResponse()) using (var stream = resp.GetResponseStream()) using (var reader = new StreamReader(stream)) {     TextBox1.Text = reader.ReadToEnd(); // or whatever } 

We get the response, get the stream, get the reader, read the stream, dispose the reader, dispose the stream, and finally, dispose the response.

Note, as commenter Nikhil Agrawal pointed out, that this is a language feature regarding blocks that is not specific to the using keyword. For example, the same applies to if blocks:

if (condition)     // may or may not execute  // definitely will execute 

Versus

if (condition1)     if (condition2)        // will execute if both are true  // definitely will execute 

Although you should never, of course, use if statements this way as it's dreadful to read, but I thought it'd help you understand the using case. I'm personally very okay with chaining using blocks.

like image 24
Matthew Haugen Avatar answered Nov 10 '22 18:11

Matthew Haugen