Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does WebResponse not have "Dispose" publically visible when it implements IDisposable?

After debugging through some code recently involving WebResponse, I found that the issue I had was that I was not properly disposing of the WebResponse before issuing another one. I was lead astray since WebResponse needs to be cast as an IDisposable in order to actually call dispose (or you can use "using" to achieve the same goal).

So my questions are:

1) What is Microsoft using to accomplish this?

IDisposable is an interface and therefore public, yet somehow WebResponse alters the access modifier to be protected according to the MSDN doumentation. I thought this was impossible.

2) What is the benefit of hiding the dispose in this manner?

Why not just let webResponse.Dispose() be valid?

like image 667
Seth Micalizzi Avatar asked Dec 09 '25 23:12

Seth Micalizzi


1 Answers

Explicit interface implementation:

public class Foo : IDisposable {
    void IDisposable.Dispose() { /* code here */ }
}

This can be done with any interface method. The using API knows to use the IDisposable implementation.

Note that this feature should not be over-used; the following would be confusing, for example:

public class Foo : IDisposable {
    void IDisposable.Dispose() { /* do something */ }
    public void Dispose() { /* do something completely different */ }
}
like image 78
Marc Gravell Avatar answered Dec 12 '25 11:12

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!