0

i have a class in which there is a method wich returns http client like below.

private HttpClient client;
private HttpClient GetClient()
    {
        if (this.client == null)
        {
            this.client = new HttpClient
            {
                 BaseAddress = new Uri("api")
            };   
            this.client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        }
            return this.client;
    }

i am using this GetClient method in other methods like

                using (var client = this.GetClient())
                {
                    var response = await client.GetAsync($"/abc").ConfigureAwait(false);
                    if (response.IsSuccessStatusCode)
                    {
                        result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                    }
                }

this client is not getting null outside the using block.next time when this method hits then client is not null.whats the problem?

sum1
  • 73
  • 5
  • Disposing doesn't mean that the object which will be disposed is getting null. It just frees the used ressources on the object. – Christoph K Nov 15 '18 at 09:39
  • Note that `using (var client ...)` creates a different `client`variable than the one declared at class scope. The `client` variable from the using declaration is not even defined outside the declaration. – Clemens Nov 15 '18 at 10:39

1 Answers1

1

Why would you expect it to be null? Disposing an object doesn't set references to it to null, it simply calls Dispose(), rendering the instance to an unusable state (when properly implemented).

See also Setting an object to null vs Dispose().

Also, don't dispose your HttpClient, read You're using HttpClient wrong and it is destabilizing your software.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • but if i use using (var client =new httpclient()) then it gives null outside scope, why so? – sum1 Nov 15 '18 at 09:52
  • and i do not have frequent calls to this method, no performance issues thats why disposing it. – sum1 Nov 15 '18 at 09:54