Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused using "using" Statement C#

According to MSDN Library

using Statement (C# Reference)
Defines a scope, outside of which an object or objects will be disposed.

But I got this code posted here by some user and I got confused about this: (please see my comment on the code)

using (OleDBConnection connection = new OleDBConnection(connectiongString))
           {
                if (connection.State != ConnectionState.Open)
                    connection.Open();
                string sql = "INSERT INTO Student (Id, Name) VALUES (@idParameter, @nameParameter)";

                using (OleDBCommand command = connection.CreateCommand())
                {
                    command.CommandText = sql;
                    command.CommandType = CommandType.Text;

                    OleDBParameter idParameter = command.CreateParameter();
                    idParameter.DbType = System.Int32;
                    idParameter.Direction = Parameterdirection.Input;
                    idParameter.Name = "@idParameter";
                    idParameter.Value = studentId; 

                    OleDBParameter nameParameter = command.CreateParameter();
                    try
                    {
                        command.ExecuteNonQuery();
                    }
                    finally
                    {
                        // Is it still necessary to dispose these objects here?
                        command.Dispose();
                        connection.Dispose();
                    }
                }
            }

In the above code, does the using statement properly used? I'm confused, can anyone please explain how to use using statement and its scoping and when, where and why to use it. Thank you..

like image 483
yonan2236 Avatar asked Oct 26 '10 08:10

yonan2236


2 Answers

The using statement is a shorthand for manually putting a try/finally block.

So

using( x ){
  ...
}

Is the same as

try{
  ...
}finally{
  if( x != null ){ x.Dispose(); }
}

And they will generate the same IL when compiled.

The compiler will give you an error in case x does not implement IDisposable.

like image 89
Øyvind Bråthen Avatar answered Nov 18 '22 05:11

Øyvind Bråthen


The finally block (and thus in this case the try) is redundant, that's what using does, it calls Dispose on the IDisposable object with which it is initialized when the using block ends (regardless of exceptions or lack thereof).

like image 11
Motti Avatar answered Nov 18 '22 04:11

Motti