is Connection.close() enough or

K

Karl Seguin [MVP]

There's a load question (loaded in the sense that it can spark a debate).

In practice, your safe doing just .Close().

But, your asking for trouble not disposing of objects that implement
IDisposable. Point in case, SqlConnection's Dispose in 2.0 seems to do more
than in 1.x (I still don't think it _has_ to be called)..but who knows what
3.0 will do, and do you really want to go back through all your code and
change it then?
Generally, ur better off just calling Dispose() (which calls close) and not
calling close. Or, use "using"

Karl
 
G

Guest

Thanks for your response, Karl.

So equivalent of
connection.close();
connection.dispose();

would be
connection.dispose(); and that would close the conneciton too..

Cool.
 
B

bruce barker \(sqlwork.com\)

Connection.Dispose calls Close. the main difference, is calling Displose
will release any event handler references. the best approach is to not call
either, but use a using statement:

using (SqlConnection conn = new SqlConnection())
{
// my code here
}

this will guarantee that the connection dispose is called, even of you have
an error, or exit the routine. as its a bad practice to pass a sqlconnection
between methods, this will keep you honest.

-- bruce (sqlwork.com)
 
G

Guest

Yes.

I use the "using" keyword, which gives neat code, and ensures that the
connection is always closed, whatever happens:

using (SqlConnection connecton = new SqlConnection(...)) {
...
...
} // when leaving here, the connection is disposed

The code that is really created is a try...finally structure with the
dispose call in the finally section. It also copies the reference to the
object, so even if you fumble badly and lose your reference to the
object, it still gets disposed. :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top