Null coalescing operator dùng với nullable value types và reference types. Dùng chuyển operand sang kiểu của nullable (hoặc không) value type operand khác, nơi implicit conversion có thể.
Nếu giá trị operand đầu tiên là null, operator trả về giá trị operand thứ hai, ngược lại trả về giá trị operand đầu tiên.
Ví dụ:
Ví dụ
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();
}
}
}
Kết quả
Value of num3: 9.77
Value of num3: 6.32123