Reputation: 13649
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..
Upvotes: 12
Views: 396
Reputation: 60694
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
.
Upvotes: 11
Reputation: 114725
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).
Upvotes: 11