Question

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());
        }
Was it helpful?

Solution

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());
    }
}

OTHER TIPS

It will be closed. Calling Dispose on SqlConnection calls Close implicitly and because you use using statement you are guaranteed that Dispose will be always called at the end of block.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top