Search code examples
c#.netidisposableexplicit-interface

Explicit implementation of IDisposable


Although there are quite a lot of Q&As regarding IDisposable to be found on SO, I haven't found an answer to this yet:

I usually follow the practice that when one of my classes owns an IDisposable object then it also implements IDisposable and calls Dispose on the owned object. However recently I came across a class which implemented IDisposable explicitly thus preventing me from directly calling Dispose forcing me to cast it which I found annoying and unnecessary.

So the question: Why and when would one want to use an explicit interface implementation of IDisposable? I know that there are perfectly good and valid reason for implementing an interface explicitly but in regards to IDisposable the reason is not quite clear to me.


Solution

  • I'd say it's unusual to have an explicit implementation of IDisposable.Dispose unless you have an alternate equivalent method (e.g. Close).

    In which case your wrapper class could call Close rather than casting.

    An example is the WebResponse class in the Framework <= V3.5. Interestingly there is a public Dispose method in .NET 4, so maybe Microsoft has now decided that an explicit implementation may not be good practice.

    Shawn Farkas, a design engineer on the CLR security team writes in MSDN magazine that

    Although the using block will work with classes that do have an explicit IDisposable implementation, I recommend that classes never implement the interface this way. If you explicitly implement IDisposable, developers who are exploring your object model using IntelliSense® in Visual Studio® will not notice that the object has a Dispose method