0

I was playing around with System.Net.HttpListenerResponse today, and I noticed that there is still apparently a gap in my knowledge regarding using.

using (HttpListenerResponse response = context.Response)
{
   // Do stuff
}

Is perfectly valid code, however, the object has no Dispose() method.

Why does using still work?

Ryan Ries
  • 2,381
  • 1
  • 24
  • 33

3 Answers3

5

IDisposable.Dispose is implemented explicitly in System.Net.HttpListenerResponse. To call it from your code you have to cast it to IDisposable first.

HttpListenerResponse response = GetResponse();

// doesn't work
response.Dispose();

// do work
((IDisposable)response).Dispose();
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
4

As you can see in its documentation, the HttpListenerResponse does implement IDisposable. The interface is implemented explicitly though, as listed under "Explicit Interface Implementations":

void IDisposable.Dispose()

As explained in C# Interfaces. Implicit implementation versus Explicit implementation:

Explicit implentation allows it to only be accessible when cast as the interface itself.

So you'll have to cast it as IDisposable in order to call the method:

((IDisposable)response).Dispose();

It is appropriately documented:

This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.

See also Why would a class implement IDisposable explicitly instead of implicitly?.

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
1

The HttpListenerResponse inherits from IDisposable thus allowing the using statements to auto call the Dispose() method when complete.

The HttpListenerResponse explicitly defines the Dispose() method as below. (Taken from decompile).

void System.IDisposable.Dispose()
{
    this.Dispose(true);
    GC.SuppressFinalize(this);
}
Nico
  • 12,493
  • 5
  • 42
  • 62