This answer to another question of mine did not compile, though on the surface it seems it should (this isn't the same question, I can rewrite the other answer to work for my other question).
Given
private Func<MyT, bool> SegmentFilter { get; set; }
public MyConstructor(Func<MyT, bool> segmentFilter = null)
{
// This does not compile
// Type or namespace mas could not be found
SegmentFilter = segmentFilter ?? (mas) => { return true; };
// This (equivalent?) form compiles just fine
if (segmentFilter == null)
{
SegmentFilter = (mas) => { return true; };
}
else
{
SegmentFilter = segmentFilter;
}
}
Why is the compiler running into trouble with the null coalescent operator, but not with the syntax-sugar-free if/else version?
The null-coalescing operator ?? returns the value of its left-hand operand if it isn't null ; otherwise, it evaluates the right-hand operand and returns its result.
The nullish coalescing operator ( ?? ) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined , and otherwise returns its left-hand side operand.
It is used for converting an operand to the type of another nullable (or not) value type operand, where an implicit conversion is possible. If the value of the first operand is null, then the operator returns the value of the second operand, otherwise, it returns the value of the first operand.
That's because ??
has higher precedence than =>
. You can easily fix that by wrapping your lambda into ()
:
SegmentFilter = segmentFilter ?? ((mas) => { return true; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With