Home >Backend Development >C++ >How Does C# 6.0's Null-Conditional Operator (?. ) Prevent NullReferenceExceptions?
C# 6.0 introduced?. The operator completely changed the method of processing vacancy. This operator solves common problems that can cause abnormalities when running an object attribute or calling the method.
<.> ?. The purpose of the operator
?. The operator, also known as the "empty condition" operator, has the following key functions:
Value check:
It evaluates whether the first operation (e.g. A) is empty. If A is empty, the operator will terminate the evaluation and return NULL.In the example above, if A is empty, the expression A? .Propertyofa would be evaluated as NULL, and the comparison with FOO would lead abnormal.
Equity
<code class="language-csharp">if (a?.PropertyOfA != foo) { //somecode }</code>In conceptual point of view, the computing symbol can be equivalent to the following code:
But,?. The operational symbol avoids the redundant assessment of A and optimized the performance of the code. Example application
Consider a scene, you have a FileInfo object FI, which may be empty or not empty. By using?. The operator, you can avoid potential abnormalities:
<code class="language-csharp">if (a != null) { a.PropertyOfA; } else { null; }</code>
In this case, if FI is empty, Length will be set to NULL without causing abnormalities.
Conclusion
C# 6.0?. The computing symbol provided an elegant and efficient solution for the processing vacancy, enabling developers to write more robust and more concise code. By providing air value inspection and member interviews at the same time in an expression, it simplifies the code structure and improves program security.
The above is the detailed content of How Does C# 6.0's Null-Conditional Operator (?. ) Prevent NullReferenceExceptions?. For more information, please follow other related articles on the PHP Chinese website!