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

WBOY
Release: 2023-09-11 19:25:02
forward
875 people have browsed it

两个问号在一起 (??) 在 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);
      }
   }
}
Copy after login

Output

The output of the above example is as follows.

Value2: 99
The value of result message is: Null Coalescing
Copy after login

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!

source:tutorialspoint.com
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!