Close of OleDBConnection in Destructor

M

Marcel Hug

Hi NG !
I would like to close my OleDBConnection in the destructor of the class,
but i get a failure, that the handle is not initialized. I read in the
msdn, that it is not good the close the oledbconnection in the finalize.
So it's the same with the destructor ?

Thanks ?
Regards
 
N

Nicholas Paldino [.NET/C# MVP]

Marcel,

It is not a destructor. It is a finalizer, which means that the object
does not get cleaned up when it goes out of scope. In this case, you need
to implement the IDisposable interface and expose an implementation of
Dispose which will close the handle when you are done with it.

Additionally, as a general rule, I wouldn't keep database references as
fields in classes anyways. I would create my connection in my method as
needed, and then close the connection when I am done with it (in the
method). If I do store it on the class level, then that says to me that the
class is a utility class which ultimately has a short life as well.

Hope this helps.
 
G

Guest

In C#, destructors are the way you implement Object.Finalize()
So the answer to your question is Yes
 
M

Marcel Hug

Hi Nicholas
It is not a destructor. It is a finalizer, which means that the object
does not get cleaned up when it goes out of scope. In this case, you need
to implement the IDisposable interface and expose an implementation of
Dispose which will close the handle when you are done with it.

Ohh thanks! I'm new in .NET programming so I'm sorry. But now I know
that I have to read the fundamental concept.
Additionally, as a general rule, I wouldn't keep database references as
fields in classes anyways. I would create my connection in my method as
needed, and then close the connection when I am done with it (in the
method). If I do store it on the class level, then that says to me that the
class is a utility class which ultimately has a short life as well.

Yes in each example I saw this kind of connecting a database. I have
changed my code now. Thanks

Regards
 

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

Top