Null-Coalescing Operator and Lambda Expression in C#

.netc++lambdanull-coalescing-operator

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?

Best Answer

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

Will work :)

It parsed it this way:

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

which does not make any sense.

Related Question