i am trying to get used to working with "using" blocks in C#, but i'm having a hard time understanding when i should be using them.
here is an example.
my original code, without the using
block:
SqlConnection conn = new SqlConnection(cCon.getConn());
SqlCommand cmd = new SqlCommand("sp_SaveSomething", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@x", xxx));
cmd.Parameters.Add(new SqlParameter("@ORG", ORG));
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{ }
finally
{
conn.Close();
}
but should i really be doing this? or should i be using(SqlConnection conn = new SqlConnection(cCon.getConn()))
? please help me understand this. is the way i'm originally doing it so wrong?
SqlConnection conn = new SqlConnection(cCon.getConn());
using( SqlCommand cmd = new SqlCommand("sp_SaveSomething", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@x", xxx));
cmd.Parameters.Add(new SqlParameter("@ORG", ORG));
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{ }
finally
{
conn.Close();
}
}