Declare IDisposable for the class or interface?

Beachwalker picture Beachwalker · May 9, 2012 · Viewed 11.9k times · Source

Starting from the follwing 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?

Answer

Ignacio Soler Garcia picture Ignacio Soler Garcia · Oct 17, 2014

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.