How to use Null Coalescing Operator (??) in C#?
Answers
Answer:
The null coalescing operator is used with the nullable value types and reference types. It is used for converting an operand to the type of another nullable (or not) value type operand, where an implicit conversion is possible.
If the value of the first operand is null, then the operator returns the value of the second operand, otherwise, it returns the value of the first operand.
The following is an example −
Example
Live Demo
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
double? num1 = null;
double? num2 = 6.32123;
double num3;
num3 = num1 ?? 9.77;
Console.WriteLine(" Value of num3: {0}", num3);
num3 = num2 ?? 9.77;
Console.WriteLine(" Value of num3: {0}", num3);
Console.ReadLine();
}
}
}
Output
Value of num3: 9.77
Value of num3: 6.32123
Explanation: