Search code examples
c#garbage-collectiondisposeidisposablefinally

Is it necessary to dispose variables in finally block in static methods?


This example below I found while looking answer to another quiestion. Here that guy disposes response in finally block. Is it really necessary? Is it a GC's work in this case?

public static async Task EnsureSuccessStatusCodeAsync(this HttpResponseMessage response)
    {
        try
        {
            if (response.IsSuccessStatusCode)
                return;
            var content = await response.Content.ReadAsStringAsync();
            throw new SimpleHttpResponseException(response.StatusCode, content);
        }
        finally
        {
            response.Content?.Dispose();
        }
    }

Solution

  • The whole point of using IDisposable is to clean up unmanaged resources that the GC can't clean up on its own. So no, you can't just let the GC clean it up because, by definition, it can't.