Why do I get about this assignment into Headers
this error
var request = new HttpRequestMessage()
{
Headers = default
};
Property or indexer 'property' cannot be assigned to -- it is read only
And it is the same even if i assign null
.
And for the following code i dont get it, ain't it also an assignment of value to `Headers` property ?
var request = new HttpRequestMessage()
{
Headers = {}
};
CodePudding user response:
You can't. That is what read-only properties are for. You cannot the change the actual reference, but you can change the value itself. Based on what the concrete type allows.
If you want to have the headers empty (which it looks like from your example), you just use request.Headers.Clear()
. And other methods alike if you want to alter/add/etc. headers.
CodePudding user response:
{}
is a collection initializer:
int[] fooBar = { };
I cannot find a proof that empty collection initializer {}
can be assigned to readonly property which has reference type.
However, this code is valid:
public class FooBar
{
public object MyProperty { get; }
}
var foo = new FooBar()
{
MyProperty = { }
};