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?

3 Answers 3

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();
Sign up to request clarification or add additional context in comments.

Comments

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?.

Comments

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.