Home  >  Article  >  Backend Development  >  What is the difference between operators ? and ?? in c#

What is the difference between operators ? and ?? in c#

下次还敢
下次还敢Original
2024-05-09 22:48:17670browse

The

? and ?? operators are conditional operators used to select values. The ? operator throws an exception if either operand is null, the ?? operator handles null values ​​safely and returns the right operand if the left operand is null.

What is the difference between operators ? and ?? in c#

The difference between operators ? and ?? in C

#The operators ? and ?? in C# are both Is a conditional operator used to select values ​​under specific conditions. However, their main difference is the mechanism for handling null values:

? operator (ternary conditional operator)

  • Syntax: condition ? value_if_true : value_if_false
  • is used to return a value when the condition is true, otherwise return another value.
  • If the condition is true, return value_if_true, otherwise return value_if_false.
  • If value_if_true or value_if_false is null, a NullReferenceException is thrown.

Example:

<code class="csharp">int? nullableValue = null;
string result = nullableValue ?? "Default value";  // result = "Default value"</code>

?? Operator (null coalescing operator)

  • Syntax :leftOperand ?? rightOperand
  • is used to return the right operand when the left operand is null.
  • If the left operand is not null, return the left operand; otherwise, return the right operand.
  • The right operand can be any value, including null.

Example:

<code class="csharp">object nullableObject = null;
object result = nullableObject ?? new object();  // result = new object()</code>

Summary

  • ? Operators used For selecting values ​​under certain conditions, an exception is thrown if either operand is null. The
  • ?? operator is used to return the right operand when the left operand is null and can handle null values ​​safely.

The above is the detailed content of What is the difference between operators ? and ?? in c#. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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
Previous article:Operator precedence in c#Next article:Operator precedence in c#