To make a simple C# 6.0 empty condition operator :?.
C# 6.0 introduced?. The operator (empty condition operator) caused widespread attention from developers. It provides an elegant way to handle vacuum references to write more concise and efficient code.
<.> ?. The computing symbols detailed
?. The core role of the operator is to prevent potential air abnormalities. Its working mechanism is as follows:
If the first operation is not empty, calculate the second operation (member interview).If the first operating number is empty, it returns null instead of throwing an exception.
In this example, the operational symbols handle the situation where A may be empty. If A is empty, A? .Prperyofa would return null to avoid subsequent comparison and triggered NullReferenceException. If A is not empty, calculate A.Propertyofa and compare it with FOO.
Similarity to conditional statements
<code class="language-csharp">public class A { public string PropertyOfA { get; set; } } ... var a = new A(); var foo = "bar"; if(a?.PropertyOfA != foo) { //somecode }</code>
The empty condition operator is similar to the simplified conditional statement:
However, the operator provides a more concise and efficient alternative.
Type conversion precautions
<code class="language-csharp">string bar = (a == null ? null : a.PropertyOfA); if (bar != foo) { ... }</code>
Summary
C# 6.0?. The operator provides a convenient and safe way to deal with vacuum references, avoiding the need to explicitly empty inspection and tedious errors in many scenarios. Using this powerful function, developers can write more robust and more efficient code, reduce the possibility of accidents and abnormalities, and improve code readability.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!