0

When using a using block for SQL connections in C#, does this also a close method? I'm asking as I need to explicitly use the con.Open() method. I found this example:

using (SqlConnection con = new SqlConnection(connectionString))
{
   con.Open(); // open method

   string queryString = "select * from db";
   SqlCommand cmd = new SqlCommand(queryString, con);
   SqlDataReader reader = cmd.ExecuteReader();
   reader.Read();

   ???         // What about a close method?
}

Or does the using block close the connection itself?

Philip Kendall
  • 4,304
  • 1
  • 23
  • 42
mnlfischer
  • 397
  • 4
  • 12
  • 26

5 Answers5

1

using translates to:

SqlConnection con = new SqlConnection(connectionString)
try
{
   con.Open(); <-- open method

   string queryString = "select * from db";
   SqlCommand cmd = new SqlCommand(queryString, con);
   SqlDataReader reader = cmd.ExecuteReader();
   reader.Read();
}
finally
{
    if (con!= null)
        ((IDisposable)con).Dispose();
}

where ((IDisposable)con.Dispose(); closes what is to be closed.

Andrey
  • 59,039
  • 12
  • 119
  • 163
0

You don't have to close it - using is enough. MSDN says:

To ensure that connections are always closed, open the connection inside of a using block, as shown in the following code fragment. Doing so ensures that the connection is automatically closed when the code exits the block.

psur
  • 4,400
  • 26
  • 36
0

No, you don't have to call the Close-Method of the SqlConnection. When it gets disposed on the end of the using, it closes automatically. (The Dispose-Method calls Close()) [1]

jAC
  • 5,195
  • 6
  • 40
  • 55
0

The other answers are correct, however, I want to be a bit more explicit.
The MSDN states the following:

Close and Dispose are functionally equivalent.

Because using using will call Dispose a separate call to Close is not needed.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
0

when you use the 'using' keyword and create a connection in it . the connection is open as far as there is the scope of the 'using' keyword when closing bracket is reached the connection is closed automatically as it was defined within a scope and the scope is not in exist

in other words treat it as the local variable which can be accessed within the scope only. hope this will help.

XTGX
  • 114
  • 9