Home >Backend Development >C++ >What Does the `??` (Null Coalescing) Operator Do in C#?
C#, "??", that is, the empty merging operator provides a simple way to assign a non -empty value to the variable. Consider the following code example:
Here, the air merger operation character is used to assign a value according to the following conditions:
<code class="language-csharp">FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();</code>
FormsAuth
In other words, if
<code class="language-csharp">FormsAuth = formsAuth != null ? formsAuth : new FormsAuthenticationWrapper();</code>; otherwise, create a new example of
and assign it to formsAuth
. This is equivalent to the following conditional statements: FormsAuth
FormsAuthenticationWrapper
FormsAuth
This structure is particularly useful when it is necessary to ensure that the variable is assigned before use. It provides a more concise and efficient alternative than using conditional statements.
<code class="language-csharp">if(formsAuth != null) FormsAuth = formsAuth; else FormsAuth = new FormsAuthenticationWrapper();</code>It should be noted that multiple air merger operators can be continuously used. For example:
In this example,
Variable will be assigned to the first non -empty<code class="language-csharp">string Answer = Answer1 ?? Answer2 ?? Answer3 ?? Answer4;</code>value. If all values are empty,
will remain empty. Answer
Answer
In addition, it is worth emphasizing that although the expansion of the air merging operator is equivalent in conceptual, each expression will only be evaluated once. This is very important when the expression involves the method of side effects. Answer
The above is the detailed content of What Does the `??` (Null Coalescing) Operator Do in C#?. For more information, please follow other related articles on the PHP Chinese website!