Home >Backend Development >C++ >How Does the C# 6.0 Null-Conditional Operator (?. ) Simplify Null Handling?
C# 6.0 introduced?. The operator brought great convenience to the air value processing. This operator is usually called the empty conditional operator, which provides a simple and secure way to access the attributes or calling methods of the empty object.
Let's take a look at the following code fragment:
Let's break down the working principle of this operator:
<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>
It first evaluates the first operation number (A) and checks whether it is empty. If A is empty, the entire expression will be evaluated as NULL and will not be further evaluated.
Consider this alternative grammar:
Although this method has reached the same result, it involves separate air values and conditional assignments. ?. The operator provides a more concise and elegant solution.
<code class="language-csharp">string bar = (a == null ? null : a.PropertyOfA); if (bar != foo) { ... }</code>
In addition, the operation symbol can change the type of expression. For example, FileInfo.Length is a long attribute. However, if you use it on it?. Operator:
You finally got a Long? Type expression, where the question mark indicates that the value may be empty. This eliminates the demand for explicit vacuum inspection, simplifies your code and improves its availability.
<code class="language-csharp">FileInfo fi = ...; // fi 可能为空 long? length = fi?.Length; // 如果 fi 为空,length 将为 null</code>
The above is the detailed content of How Does the C# 6.0 Null-Conditional Operator (?. ) Simplify Null Handling?. For more information, please follow other related articles on the PHP Chinese website!