Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null Coalescence and Lambdas

Tags:

c#

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?

like image 844
Eric J. Avatar asked Sep 22 '15 22:09

Eric J.


People also ask

Why we use null coalescing operator?

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.

Which is null coalescing operator?

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.

What is coalescing in c#?

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.


1 Answers

That's because ?? has higher precedence than =>. You can easily fix that by wrapping your lambda into ():

SegmentFilter = segmentFilter ?? ((mas) => { return true; });
like image 138
MarcinJuraszek Avatar answered Sep 16 '22 15:09

MarcinJuraszek