Search code examples
c#.netdisposeidisposable

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

  • 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".