Home  >  Article  >  Backend Development  >  What does two question marks together (??) mean in C#?

What does two question marks together (??) mean in C#?

WBOY
WBOYforward
2023-09-11 19:25:02853browse

两个问号在一起 (??) 在 C# 中意味着什么?

This is the null-coalescing operator. The null-coalescing operator returns the value of its left operand if the left operand is not null; otherwise, it evaluates the right operand and returns its result. The ?? operator does not evaluate its right operand if the left operand evaluates to non-null.

Nullable types can represent undefined or values ​​from the type domain. When the left operand has a nullable type, we can use the ?? operator to return the appropriate value. If we try to assign a nullable value type to a non-nullable value type without using the ?? operator, we will get a compile-time error and if we force a cast, an InvalidOperationException will be thrown.

Following are the advantages of Null-Coalescing operator (??) -

  • It is used to define default values ​​for nullable items (value types and reference types).

  • It prevents InvalidOperationException exceptions at runtime.

  • It helps us eliminate many redundant "if" conditions.

  • It applies to reference types and value types.

  • The code becomes organized and readable.

Example

Demonstration

using System;
namespace MyApplication{
   class Program{
      static void Main(string[] args){
         int? value1 = null;
         int value2 = value1 ?? 99;
         Console.WriteLine("Value2: " + value2);
         string testString = "Null Coalescing";
         string resultString = testString ?? "Original string is null";
         Console.WriteLine("The value of result message is: " + resultString);
      }
   }
}

Output

The output of the above example is as follows.

Value2: 99
The value of result message is: Null Coalescing

The above is the detailed content of What does two question marks together (??) mean in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete