Question

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?

Was it helpful?

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 
}

OTHER TIPS

curly brackets just show a code of block

where as Using instructs the GC to dispose.

Any class that implements IDisposable can be used with Using.

using will essentially translate to (note no catch). If there is any exception it will be thrown out. but even then connection will dispose

SqlConnection conn;
try
{
    conn = new SqlConnection(connString);
}
finally
{
    if (conn != null)
        conn.Dispose();
}

namespace changes name lookup whereas curly brackets create a new stack in which local variables may be created.

If you use version with key using, then NET platform runs method Dispose to free resources which the object used. So the object must implement IDisposable interface. In this way you free the resources in deterministic way (unlike Garbage Collector do it).

It is highly recommended to clean NOT managed resources in method Dispose, because GC does not clean it.

Curly brackets determine only the scope of variables used inside of them, but does not clean resources after the runtime reaches the close bracket. GC does it in non deterministic way according to its algorithms.

When you use

using( ...){
... code
}

this is actually using pattern, c# compiler emits code to invoke the dispose method implemented by object created in the using block.

So for any object implementing IDisposable interface, you can use

using(var disposableObject = new DisposableObject()){
}

when this compiles compliler will generage code below

DisposableObject disposableObject = null;
try
{
   disposableObject = new DisposableObject();
}
finally{
   disposableObject.Dispose();
}

So using (..) statement ensure that dispose method of disposable object is called even if any exception is thrown within using statement.

using is equivalent to following

SqlConnection conn;
try
{
   conn = new SqlConnection(connString)
}

finally
{
  conn.Dispose() //using does this automatically for you
}

The rule is when some class implements IDisposable you can use USing block instead of try catch, finally pattern

If you want more insight on how GC works, read this excellent article by Jeffery Richter

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top