Reputation: 21538
I have a class that has a DbConnection
variable. In the class constructor I assign a new DbConnection
instance to it. Since it is an IDisposable
, am I supposed to do something with it at my class's destructor (or somewhere else)?
I know that if using it it one piece of code I am supposed to wrap it in a using
block, tough I am not sure why, but here I am assigning it once and using it for all calls to my class.
If it makes any difference, I am using C# 4.0.
Upvotes: 2
Views: 214
Reputation: 431
surrounding ur dbconnection with "using" code block automatically dispose'es any open connection
using(sqlConnection conn=new SqlConnection(connectionstring)){
//rest of the code here
}
Upvotes: 0
Reputation: 3379
This article might be helpful - Implementing a Dispose Method
Basically classes that implement IDisposable
have dependencies on some resources that needs to be fried when not needed any more. In your case that's connection to database. It would be not wise to keep connection open all the time. If you are using it inside using
block - it will dispose object at the end of the block (it is syntactic sugar for try finally
construction). If you hold it as object field/property - best idea is for your class to also implement IDisposable
and make sure that the user of your class disposes it correctly.
Side note - you can dispose your objects in finalizers, but that's highly not recommended for normal workflow, so please do not go that way.
Upvotes: 0
Reputation: 1503290
Since it is an IDisposable, am I supposed to do something with it at my class's destructor (or somewhere else)?
No, typically you won't have a finalizer/destructor - they're almost never needed in modern .NET.
However, your class should implement IDisposable
, and dispose of the database connection there. That way you're basically passing on the responsibility for disposing to whoever creates an instance of your class.
Upvotes: 7
Reputation: 13217
All classes that deal with non-managed resources implement IDisposable
. This way you make sure that unmanaged resources are being released after their use by either using() {}
or calling the Dispose
-method.
From MSDN
IDisposable Interface - Defines a method to release allocated resources.
Upvotes: 0