It's a very simple question..I want to know based on the code below..Is the connection closed and then return estatement will be executed or the return estatement will be executed without closing the connection?..because I set the CommandBehavior
to close the connection, but I think the connection will not be close at all..Am I right?
using (var con = new SqlConnection(_constr))
{
con.Open();
var cmd = new SqlCommand(cmdstr, con);
var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (reader.Read())
return Convert.ToInt32(reader["persianDate"].ToString());
}
the associated Connection object is closed when the associated DataReader object is closed.
since you are not closing data reader before return there is no affect using CommandBehavior.CloseConnection
but your using
block will close the connection.
I would add using
blocks for both SqlCommand
and Reader
as well
using (var con = new SqlConnection(_constr))
using (var cmd = new SqlCommand(cmdstr, con))
{
con.Open();
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
return Convert.ToInt32(reader["persianDate"].ToString());
}
}