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,274
  • 1
  • 22
  • 40
mnlfischer
  • 397
  • 3
  • 11
  • 26

5 Answers5

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,243
  • 25
  • 36
0

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
  • 57,904
  • 11
  • 115
  • 158
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,000
  • 6
  • 41
  • 52
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
  • 166,158
  • 40
  • 312
  • 426
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