While searching around for how to work with HTTP request headers, i've seen a ton of examples use this construct to initialize the HttpRequestMessage:
var request = new HttpRequestMessage()
{
Headers =
{
{ HttpRequestHeader.Authorization.ToString(), Token },
{ HttpRequestHeader.ContentType.ToString(), "multipart/form-data" }
},
Method = HttpMethod.Post,
RequestUri = new Uri(endpointUrl),
Content = content
};
This seems to work fine, and the compiler isn't complaining, not even registering a warning, but i'm very confused about the Headers field initialization.
The Headers field in the source code is defined as:
public HttpRequestHeaders Headers
{
get
{
if (headers == null)
{
headers = new HttpRequestHeaders();
}
return headers;
}
}
I'm wondering, how is it possible to initialize a field that only has a get function?
Even if it's somehow initializing the underlying private HttpRequestHeaders headers (even though i'm pretty sure it doesn't work like that), i've never seen the Field = { { ... }, { ... } } type of initialization in C#.
It's reminiscent of the Dictionary initializer, but it's missing the new HttpRequestHeaders for that to be the case.
This is the first and only time i've seen this type of initialization and cannot find any reference to it in the docs or on SO.
HttpRequestHeader implements
System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string,System.Collections.Generic.IEnumerable<string>>>That means you can add elements to this, in this case
KeyValuePair-Elements. You are not initializing the Headers-Property, you add KeyValuePairs to it.See https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers#object-initializers-with-collection-read-only-property-initialization