15

HttpWebReponse implements IDisposable interface, but why is there no Dispose method. It only contains Close method. Will be using pattern still available for this class?

Jehof
  • 34,674
  • 10
  • 123
  • 155
user705414
  • 20,472
  • 39
  • 112
  • 155
  • The [HttpWebResponse](http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.aspx) should be a Dispose method, as specified here: [WebResponse.Dispose Method @ msdn](http://msdn.microsoft.com/en-us/library/ff928381.aspx) – Ron Sijm Nov 09 '11 at 10:22
  • BTW - Perhaps this changed at some point. now `HttpWebResponse response = ...;'` `response.Dispose();` compiles. – ToolmakerSteve Jan 16 '17 at 17:00

1 Answers1

25

HttpWebResponse implements IDisposable interface explicitly. So you can call Dispose only when you cast HttpWebResponse to IDisposable. The Close method of HttpWebResponse calls Dispose internally.

HttpWebResponse response = // assigned from somewhere
IDisposable disposableResponse = response as IDisposable;

disposableResponse.Dispose();

Since HttpWebResponse implements IDisposable you can use it with an using-statement.

HttpWebResponse response = // assigned from somewhere

using(response) {
  // do your work;
}
Jehof
  • 34,674
  • 10
  • 123
  • 155
  • @user705414: see this questio on stackoverflow http://stackoverflow.com/questions/143405/c-interfaces-implicit-and-explicit-implementation – Jehof Nov 09 '11 at 11:20
  • why is it implemented explicitly? – jgauffin Nov 09 '11 at 14:02
  • 4
    @jgauffin, because (someone at) Microsoft thinks it will make your code more readable to write `response.Close();` instead of `response.Dispose();`. The same reason that all IO/stream classes must be `Close`d. – GvS Nov 09 '11 at 14:09
  • It seems that the opposite is true. `Dispose()` calls `Close()` internally. Source: https://referencesource.microsoft.com/#System/net/System/Net/WebResponse.cs,fb515b1af6c9f830 – Delphi.Boy May 13 '20 at 16:39