Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Designing an interface where only some implementations require IDisposable [closed]

Tags:

c#

.net

You are designing an interface IFoo

public interface IFoo
{
   void Bar();
}

Let's say there are five implementations of this interface. Two of those implementations should also implement IDisposable as they use unmanaged resources. From a caller's perspective, it would be easiest if IFoo implemented IDisposable so any IFoo can be wrapped in a using block, but of course some of the implementations would then be littered with empty Dispose() methods. Just curious are there other ways of doing this?

like image 413
Peter Kelly Avatar asked Aug 30 '11 11:08

Peter Kelly


1 Answers

I suspect I'd simply demand IDisposable() - a no-op Dispose() isn't a big overhead.

If you can't be sure whether it is disposable, the following is pretty effective:

var mightBeDisposable = GetBlah();
using(mightBeDisposable as IDisposable)
{
   // etc
}
like image 112
Marc Gravell Avatar answered Oct 07 '22 00:10

Marc Gravell