Reputation: 26071
I want to created a method that calls a repository class in a using() statement. That class is not currently disposable. Is there anything I should consider before making it implement IDisposable?
i.e.
using(var repo = new RespositoryClass() )
{
//do work
}
Upvotes: 1
Views: 139
Reputation: 46047
You should implement IDisposable
if the class uses unmanaged resources, or initializes other members that implement it. Otherwise, don't use it if you don't need it.
Upvotes: 3
Reputation: 203829
Just because you use an IDisposable
object inside a class does not mean that the class needs to implement IDisposable.
The example class below doesn't need to implement IDisposable
.
class NotDisposable
{
public void someMethod()
{
using(SomethingDisposable resource = new SomethingDisposable ())
{...}
}
}
Here is an example of a class that would need to implement IDisposable
.
class SomethingToDispose : IDisposable
{
private SomethingDisposable resource = new SomethingDisposable();
public void someMethod()
{
//code that uses resource
}
//code to dispose of "resource" in a Dispose method.
}
As you can see in this second example there isn't really anywhere for the class to put a using
statement to dispose of the resource. Since it's storing the disposable object in a field, and it is the one responsible for disposing of it, the best way of ensuring that it gets disposed is to implement IDisposable
.
Upvotes: 2