Click here to Skip to main content
15,907,687 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all, please See my Code snippet:

My Question is: When I use  "using()"  do i explicitly need to close the connection object?  

As i read in documentation, objects will be cleared automatically. Am I doing something wrong?

C#
protected void cmdRegister_Click(object sender, EventArgs e)
   {
       int Userid = 0;
       using (SqlConnection Cn = new SqlConnection(str))
       {

           using (SqlCommand Cmd = new SqlCommand("Insert_User"))
           {
               Cmd.CommandType = CommandType.StoredProcedure;
               Cmd.Parameters.AddWithValue("@Username", txtUsername.Text);
               Cmd.Parameters.AddWithValue("@Password", txtPassword.Text);
               Cn.Open();
               Userid = Convert.ToInt32(Cmd.ExecuteScalar());
               Cn.Close();
           }
       }
   }
Posted
Updated 21-Aug-15 3:03am
v2

1 solution

Default implementation of dispose in all database classes takes care of closing the connection.

If you write your own class which also overrides default Dispose method, you have to take care to clean up after yourself.

In the example above, you're not doing any damage, but also nothing useful.

Here is
MS docs[^] for connection closing.

Microsoft: "The connection is automatically closed at the end of the using block."
 
Share this answer
 
Comments
Kiran2401 21-Aug-15 9:10am    
Thank You very much for Your guide.
Sinisa Hajnal 21-Aug-15 9:12am    
No problem. Feel free to accept this as a solution ;)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900