Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null-coalescing operator and lambda expression

take a look at the following code I attempted to write inside a constructor:

private Predicate<string> _isValid;

//...

Predicate<string> isValid = //...;
this._isValid = isValid ?? s => true;

The code doesn't compile - just "invalid expression term"s and so one.

In contrast that does compile and I could just use it:

this._isValid = isValid ?? new Predicate<string>(s => true);

However, I still wonder why this syntax is not allowed.

Any ideas?

like image 653
Matthias Avatar asked Jul 10 '10 06:07

Matthias


2 Answers

this._isValid = isValid ?? (s => true);

Will work :)

It parsed it this way:

this._isValid = (isValid ?? s) => true;

which does not make any sense.

like image 189
Lasse Espeholt Avatar answered Nov 03 '22 03:11

Lasse Espeholt


Check out this portion of the C# grammar:

parenthesized-expression:
    (   expression   )

.....

simple-name:
    identifier   type-argument-listopt

.....

conditional-or-expression:
    conditional-and-expression
    conditional-or-expression   ||   conditional-and-expression

null-coalescing-expression:
    conditional-or-expression
    conditional-or-expression   ??   null-coalescing-expression

conditional-expression:
    null-coalescing-expression
    null-coalescing-expression   ?   expression   :   expression

lambda-expression:
    anonymous-function-signature   =>   anonymous-function-body

Since null-coalescing-expression terminates with conditional-or-expression the s in your example will parse as a simple-name. By wrapping it in parentheses it can then be parsed as a parenthesized-expression.

like image 39
ChaosPandion Avatar answered Nov 03 '22 03:11

ChaosPandion