Null-coalescing operator and lambda expression

天涯浪子 提交于 2019-11-28 11:11:41
this._isValid = isValid ?? (s => true);

Will work :)

It parsed it this way:

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

which does not make any sense.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!