开发者

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;
  开发者_如何学JAVA                  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..


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.


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜