Tip #014
Assign if null with ??=
About this tip
?? 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 coffeeCode
string? name = null;
var shown = name ?? "stranger";Console.WriteLine(shown);
name ??= "Khalid";name ??= "Nicole";Console.WriteLine(name);Output
$ dotnet run coalesce.csstrangerKhalid