Does "using" automatically close SqlConnection

  • Thread starter Thread starter John Bailo
  • Start date Start date
J

John Bailo

using (
SqlCommand cmd = new SqlCommand("select * sample"),
new SqlConnection( sqlDsn )
)
)

{
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
}

Does the SqlConnection automatically get closed when I exit the using?
 
In your specific scenario the SqlConnection will be closed but not by the
using statement. The SqlCommand will close the SqlConnection when it is
disposed by the using statement.
The SqlCommand will only close the SqlConnection if it opened the connection
itself. So if the connection was already open before it was passed as a
parameter to the SqlCommand it will not be closed by the SqlCommand.

Sandor
 
Back
Top