Take this code sample:
string status = "ok";
SqlCommand cmd=null;
SqlTransaction trans=null;
try
{
cmd = defs.prepquery("");
trans = cmd.Connection.BeginTransaction();
cmd.Transaction = trans;
}
catch (Exception ex)
{
status = defs.logerror("initalizing sql transaction:" + ex.ToString());
return status;
}
try
{
if (oper == "submit")
{
cmd.CommandText = "update DCM_Mapping_Sessions set StatusID=2 " +
"where MappingSessionID=" + mpsid + "";
cmd.ExecuteNonQuery();
}
else if (oper == "delete")
{
// .......etc etc
}
catch(Exception ex2)
{
//rollback , close the connection
// handle the ex
}
// if everything is ok , comit the transaction and close the connection
}
So my question is: What happens with the objects in the try block when an exception occurs ?
Does C# allows me to be lazy and destroys the objects(destroying the pending transaction meaning rollback) and closes the connection if an exception occurs ?
I come from a C\C++ background so i am doing my stuff as above to be safe and not end with a transaction open if an exception occurs somewhere below.
You should be disposing/closing the connection and transaction.
The best way to do so is to wrap the creation in a
usingstatement.In essence a
usingstatement wraps the creation of the objects intry{}finally{}blocks to ensure proper disposal.