问题
Example 1:
var ca = p.GetCustomAttribute<ConnectorAttribute>();
return ca?.Point.IsEqual(cp) ?? false;
Example 2:
var ca = p.GetCustomAttribute<ConnectorAttribute>();
return (null != ca) && ca.Point.IsEqual(cp);
Question:
- Does the two example return the same result?
- Which one performs better?
- Are there any concerns about thread safety?
Edit: Nobody mention but the title had some error, I've corrected it.
Edit 2: According the comments, 'those code are the same'. For me it is still not as trivial as it seams to be.
The answer here tells that the first part of example 1. creates a Nullable<bool>
type. Is it optimized because of the null-coalescing operator?
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/49853515/null-condition-and-null-coalescing-operator-vs-plain-boolean-notation