Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would a class implement IDisposable explicitly instead of implicitly?

I was using the FtpWebResponse class and didn't see a Dispose method. It turns out that the class implements IDisposable, but does so explicitly so that you must first cast your instance to IDisposable before calling Dispose:

// response is an instance of FtpWebResposne
((IDisposable) response).Dispose();

Why would the designer of a class such as this one choose to implement IDisposable explicitly? As Anthony Pegram says, doing things this way masks the fact that the object should be disposed for the average developer who is not consulting the documentation every time he/she uses a class.

like image 497
MCS Avatar asked Jun 25 '10 15:06

MCS


2 Answers

This is normally done if the class has a Close method that is the exact same as Dispose. The original Dispose is hidden in an explicit implementation so that the exact same method doesn't have two names.

It's officially recommended here:

Do implement a Close method for cleanup purposes if such terminology is standard, for example as with a file or socket. When doing so, it is recommended that you make the Close implementation identical to Dispose...

Consider implementing interface members explicitly to hide a member and add an equivalent member with a better name.

Occasionally a domain-specific name is more appropriate than Dispose. For example, a file encapsulation might want to use the method name Close. In this case, implement Dispose privately and create a public Close method that calls Dispose.

(P.S. I disagree with this convention.)

like image 78
Stephen Cleary Avatar answered Sep 23 '22 20:09

Stephen Cleary


  • Occasionally a class will have a Dispose method that is part of the interface but doesn't actually need to be called because the only resource to dispose of is memory: MemoryStream, for example.
  • As mentioned by others, if the class has a Close method that does the same thing as Dispose, arguably Dispose only needs to exist to support the "using" pattern so it may as well be explicit.
like image 29
Qwertie Avatar answered Sep 23 '22 20:09

Qwertie