Home > Backend Development > C++ > What is the C# Null Coalescing Operator (??) and How Does it Work?

What is the C# Null Coalescing Operator (??) and How Does it Work?

DDD
Release: 2025-01-29 08:15:10
Original
409 people have browsed it

What is the C# Null Coalescing Operator (??) and How Does it Work?

The empty merger operation symbol in the c#: the mystery of the dual question mark

In the field of C# programming, you may encounter a special syntax containing two question marks ("??"). This mysterious symbol is called an air merger computing, which is worth studying carefully.

Air merging operational symbol: Overview

The function of the air merger (represented by "??" is similar to the three yuan (immediately if) operator. It allows you to simply specify the reserve value used on the left expression calculation result.

Context examples

Consider the following code fragment:

Here, the empty merger computing character is used to set the value of FormsAnce variable to formsAuth (if it is not empty) or a new FormsAuthenticationWrapper instance (if Formsauth is empty).

The conditional statement of the extension is equivalent
FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
Copy after login

In order to better understand the behavior of the air merger operator, we can expand it into an equivalent conditional statement:

<一> Further simplify

This condition statement can be further written:
FormsAuth = formsAuth != null ? formsAuth : new FormsAuthenticationWrapper();
Copy after login

Therefore, the air merger computing character is essentially a shortcut to the if-Art S statement, which provides a simple way to specify the backup value.

<联> Class joint air merger operation symbol

if (formsAuth != null)
    FormsAuth = formsAuth;
else
    FormsAuth = new FormsAuthenticationWrapper();
Copy after login
You can link multiple air merger computing to check the empty value in turn. For example:

This statement assigns the first non -empty ANSWER# to ANSWER variable. If all ANSWER# values ​​are empty, the ANSWER variable is kept empty. <能> Performance precautions

It should be noted that the air merger operator only evaluates its expression once, whether they are true or false. This may be beneficial when one of the expressions has side effects.
string Answer = Answer1 ?? Answer2 ?? Answer3 ?? Answer4;
Copy after login

The above is the detailed content of What is the C# Null Coalescing Operator (??) and How Does it Work?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template