Declare IDisposable for the class or interface?
Starting from the following situation:
public interface ISample
{
}
public class SampleA : ISample
{
// has some (unmanaged) resources that needs to be disposed
}
public class SampleB : ISample
{
// has no resources that needs to be disposed
}
The class SampleA should implement the interface IDisposable for releasing resources. You could solve this in two ways:
1. Add the required interface to the class SampleA:
public class SampleA : ISample, IDisposable
{
// has some (unmanaged) resources that needs to be disposed
}
2. Add it to the interface ISample and force derived classes to implement it:
public interface ISample : IDisposable
{
}
If you put it into the interface, you force any implementation to implement IDisposable even if they have nothing to dispose. On the other hand, it is very clear to see that the concrete implementation of an interface requires a dispose/using block and you don't need to cast as IDisposable for cleaning up. There might be some more pros/cons in both ways... why would you suggest to use one way preferred to the other?
Solution 1:
Following the Inteface Segregation Principle of SOLID if you add the IDisposable to the interface you are giving methods to clients that are not interested in so you should add it to A.
Apart from that, an interface is never disposable because disposability is something related with the concrete implementation of the interface, never with the interface itself.
Any interface can be potentially implemented with or without elements that need to be disposed.
Solution 2:
If you apply the using(){}
pattern to all your interfaces it's best to have ISample
derive from IDisposable
because the rule of thumb when designing interfaces is to favor "ease-of-use" over "ease-of-implementation".