skip to content
Khalid Abuhakmeh logo Khalid Abuhakmeh

Assign if null with ??=

C# 8

Code card: Assign if null with ??=. Program output: stranger / Khalid

?? gives a fallback value. ??= assigns only when the variable is null, so the second one does nothing. It is available since C# 8. The key line is name ??= "Khalid" in coalesce.cs. Run it and the output reads stranger, Khalid.

Did this tip save you some time? Consider buying me a coffee to fuel the next one.

Buy me a coffee
coalesce.cs
string? name = null;
var shown = name ?? "stranger";
Console.WriteLine(shown);
name ??= "Khalid";
name ??= "Nicole";
Console.WriteLine(name);
Output
$ dotnet run coalesce.cs
stranger
Khalid