I can call a method defined in the HttpClientExtensions class, but invoking it on an object of type HttpClient. How does that work?

Found several examples of this, imitated it blindly and it works. But… how????

HttpClientHandler httpClientHandler = new HttpClientHandler() { Credentials = new NetworkCredential(username, password) }; HttpClient httpClient = new HttpClient(httpClientHandler) { BaseAddress = new Uri(address) }; //... fancy stuff Task<HttpResponseMessage> t = httpClient.PostAsync<List<MyObj>>( address, l, new XmlMediaTypeFormatter()); 

The point is that PostAsync<T>() is defined in the HttpClientExtensions class, which does not inherit from HttpClient and even if it did, the object was created as a plain HttpClient. It works, though.

Is it because of the way in which the first parameter is declared?

public static Task<HttpResponseMessage> PostAsync<T>( this HttpClient client, string requestUri, T value, MediaTypeFormatter formatter); 

What does the "this" keyword mean in this context? Is it like saying "call me on objects of type x" ?

by redrainyskies via /r/csharp

Leave a Reply