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

非 Y 不嫁゛ 提交于 2019-12-02 08:26:00

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.

To answer you question (null != ca) is equal to ca? as ?(this gives more readability and shorter version) it operator just check the value is null or not , Not sure but compiler underthe hood doing same thing , you can check using reflector.

Just to not both will give you same result and performs also be same , it just compiler of C# which under the hood replace ? with null check.

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