Why can I omit the subsequent null-conditional operators in an invocation chain?

后端 未结 2 1930
面向向阳花
面向向阳花 2021-01-16 01:57

Consider the following code:

IEnumerable xx = null;
var tt = xx?.Where(x => x > 2).Select(x => x.ToString());

It assign

2条回答
  •  醉话见心
    2021-01-16 02:18

    Yes, this is due to short-circuiting. From the MSDN reference:

    ...[T]he null-condition operators are short-circuiting. If one operation in a chain of conditional member access and index operation returns null, then the rest of the chain’s execution stops.

    The reason your second example throws is because you have separate unchained statements. Short-circuiting cannot be applied across multiple statements.

提交回复
热议问题