destructors,closing connections

J

juli

Hello ppl!
How exactly do I close all the database connections that was open in
the config file and how do I use the destructor in C#.
Thanks a lot!
 
N

Nicholas Paldino [.NET/C# MVP]

juli,

The config file does not open database connections, you have to do that
explicitly in your code.

In C#, there is no destructor, rather, the term is "finalizer". This is
important, because the difference goes way beyond just a name change. The
finalizer is called when an object is collected by the garbage collector, it
doesn't get called when it goes out of scope. Because of this, you will
have to explicitly release the connection when you are done with it.

For this purpose, MS defined the IDisposable interface, indicating that
an object needs to be closed explicitly. To make it easier to use in C#,
there is the "using" statement as well.

For more information, check out the section of the .NET framework titled
"Implementing a Dispose Method", located at (watch for line wrap):

http://msdn.microsoft.com/library/d...guide/html/cpconimplementingdisposemethod.asp

Hope this helps.
 
S

Scott Allen

Hi juli:

The config file doesn't open a database connection, your C# code does.

The easiest way to ensure a connection is closed is with the using
clause:

using(SqlConnection connection = new SqlConnection(...))
{
// put connection to work
}

The using block ensures a Dispose method is called even if there is an
exception. Dispose for a SqlConnection will clean up the connection,
and return the connection to the free pool by default.
 

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

Similar Threads


Top