This code will not compile:
var x = new {
Property = null,
};
With following exception: Cannot assign null to anonymous type property
But this will work fine:
var someBool = false;
var x = new {
Property = someBool ? "value" : null,
};
I think there is implicit casting something like this - (string)null but not exactly sure.
So I would like to know more about this case and how this works internally (I didn't find any article explaining this)
Compiler needs to determine type for anonymous type's properties which can't be done from just
null(though you can argue about usingobjectin this case but see the following quote), on the contrary ternary operator has a type (see the linked docs explaining how compiler determines it), which isstringin case ofsomeBool ? "value" : null.From anonymous types doc: