Search code examples
c#scopeusingcurly-braces

"using" statement vs. curly brackets


I wonder why we do use using statement in C#. I looked it up, and found that it is used for executing the statements and then cleaning up the objects. So my question: Isn't it the same thing if we open and close curly brackets( { } ) to define a scope?

Using statement:

using (SqlConnection conn = new SqlConnection(connString)) {
     SqlCommand cmd = conn.CreateCommand();
     cmd.CommandText = "SELECT * FROM Customers";
     conn.Open();
     using (SqlDataReader dr = cmd.ExecuteReader()) {
          while (dr.Read()) 
          // Do Something...
     }
}

Curly Brackets:

{
     SqlConnection conn = new SqlConnection(connString);
     SqlCommand cmd = conn.CreateCommand();
     cmd.CommandText = "SELECT * FROM Customers";
     conn.Open();
     {
          SqlDataReader dr = cmd.ExecuteReader();
          while (dr.Read()) 
          // Do Something...
     }
}

Are there any significant differences between two methods?


Solution

  • Well, using (which is legal if and only if the class implements IDisposable interface)

    using (SqlConnection conn = new SqlConnection(connString)) {
      // Some Code
      ...
    }
    

    is equal to this block of code

    SqlConnection conn = null;
    
    try {
      SqlConnection conn = new SqlConnection(connString);
    
      // Some Code
      ...
    }
    finally {
      if (!Object.ReferenceEquals(null, conn))
        conn.Dispose();
    }
    

    C# doesn't have the same behavior as C++ does, so do not use {...} pattern in C# as you do in C++:

    {
      SqlConnection conn = new SqlConnection(connString);
      ...
      // Here at {...} block exit system's behavior is quite different:
      //
      // C++: conn destructor will be called, 
      // resources (db connection) will be safely freed
      //
      // C#:  nothing will have happened! 
      // Sometimes later on (if only!) GC (garbage collector) 
      // will collect conn istance and free resources (db connection). 
      // So, in case of C#, we have a resource leak 
    }