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

后端 未结 2 1909
面向向阳花
面向向阳花 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:10

    The null-conditional operator or also known as the null propagation operator is short-circuiting i.e if one operation in the chain:

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

    returns null, then the rest of the chain’s execution stops.

    So in the above example Where is never invoked as xx is null.

    As for the second example, you're getting an ArgumentNullException because that's the behaviour of extension methods. in this specific case, the Select throws a ArgumentNullException when the source or the provided selector is null.

提交回复
热议问题