2013-08-09

Difference between Dispose and Close methods

Most of the time, we use those methods interchangeably without knowing the true context of them. Sometimes we call both of the methods. So let’s see what are the difference between those two methods and whether we should call both of the methods when we need to close a connection. I will take an SQL connection as the example,

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Test"].ToString());
con.Open();
con.Close();
con.Open(); //2nd attempt

In the above code, the 2nd attempt would not fail. Close will simply close the connection. But it does not necessarily release the memory and do the clean up (It will release the resources temporarily). So it's possible for you to open the same connection again. Now let's use the Dispose instead and see the result

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Test"].ToString());
con.Open();
con.Dispose();
con.Open(); //2nd attempt

Now on the 2nd attempt, it will throw me an exception saying "The ConnectionString property has not been initialized.". Why is that? That's because I have already release all the resources including the Connection String, by calling the Dispose method.

So when you are really done with a connection (If you do not wish to open it again), you should call Dispose method. It will implicitly call the Close method.

No comments: