Null-condition and null-coalescing operator *vs.* plain boolean notation

后端 未结 2 394
别那么骄傲
别那么骄傲 2021-01-26 02:41

Example 1:

var ca = p.GetCustomAttribute();
return ca?.Point.IsEqual(cp) ?? false;

Example 2:

var ca          


        
2条回答
  •  攒了一身酷
    2021-01-26 03:29

    Answer to your first question: Yes.

    Short answer to your second question: None, you should choose based on which is more readable.

    Answer to your third question: if you expect the whole expression to run "in one shot" and therefore not be subject to concurrency issues, then no, the null-coalescing operator does not guarantee that as explained in the answer of this Stackoverflow question. In both your examples you would actually face the same concurrency challenges.

    Long answer to your second question:

    Looking in the Microsoft '??' doc, all is mentioned is the operator purpose and function:

    The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.

    Hence, the null-coalescing operator makes you write cleaner code that would otherwise require you to write the operand in question twice (as in your 2nd example).

    Usage of the null-coalescing operator is more related to utility than performance, as explained is the accepted answer of a similar Stackoverflow question. Indeed, both perform quite the same.

    Interesting to notice, as part of the same answer, the null-coalescing operator seems to perform slightly faster, but the difference is so little that could be ignored.

提交回复
热议问题