-
Null-Coalescing Operator (??)
It is a shorthand to check if the variable is null before accessing its value.
int? i = null;
string? temp="I'm not null!";
int index = i ?? 0;
string result = temp ?? "Null";
Console.WriteLine(index);
Console.WriteLine(result);
Console.ReadLine();
// 0
// I'm not null!
-
Null-Coalescing Assignment Operator (??=)
int? i = null;
string? temp="I'm not null!";
int index = i ?? 0;
string result = temp ?? "Null";
Console.WriteLine(index);
Console.WriteLine(result);
i ??= 100;
temp ??= "Hello!";
Console.WriteLine(i);
Console.WriteLine(temp);
Console.ReadLine();
// 0
// I 'm not null!
// 100
// I 'm not null!
-
Null Conditional Operator (?.)
With this (?.), if the variable is null, its call to the Length property will not throw a runtime error.
NullConditionalOp(null);
Console.ReadLine();
static void NullConditionalOp(string[] args)
{
Console.WriteLine($"There are {args?.Length ?? 0} arguments.");
// if args is null, it will not access the Length but assign 0.
}