Search code examples
c#.net.net-6.0idisposableusing-statement

Should I wrap new HttpRequestMessage() in a using statement?


I found the following code:

using (var requestMessage = new HttpRequestMessage(HttpMethod.Delete, endpoint))
{
    ...
    HttpResponseMessage response = await _client.SendAsync(requestMessage);
    ...
}

I haven't seen this pattern before.

I know System.Net.Http.HttpRequestMessage implements IDisposable, but does that mean we should wrap it in a using statement?


Solution

  • Yes you should. The documentation endorses this practice.

    If your app simply uses an object that implements the IDisposable interface, you should call the object's IDisposable.Dispose implementation when you are finished using it. Depending on your programming language, you can do this in one of two ways:

    • By using a language construct such as the using statement in C# and Visual Basic, and the use statement or using function in F#.
    • By wrapping the call to the IDisposable.Dispose implementation in a try/finally block.

    You don't have to "wrap" the block of code in a using statement, though. Since C# 8, you can also use the using declaration. Just declare a regular variable, and add using at the start.

    The reason why HttpRequestMessage implements IDisposable is because its Content is IDisposable. Why does HttpContent need to be disposed then? Because you could read the content as a Stream, or supply the content as a Stream, using its subclass StreamContent. Check out the source code for these APIs for more information. These all involve a stream that needs to be disposed. One can create their own subclass of HttpContent that uses a resource that needs to be disposed.

    Technically, if you are not doing any of the above things, HttpRequestMessage.Dispose doesn't do anything, but who knows what might change in the future?