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