Search code examples
c#c#-8.0null-check

Short cut for a check for null and assigning a value to it if it is?


With the new C# 8 capabilities is there a short cut now for this null-check code structure?

if (App.selectedPhrases == null)
    App.selectedPhrases = App.DB.GetSelectedPhrases();

Solution

  • Yes, it is called Null-coalescing assignment:

    App.selectedPhrases ??= App.DB.GetSelectedPhrases();
    

    C# 8.0 introduces the null-coalescing assignment operator ??=. You can use the ??= operator to assign the value of its right-hand operand to its left-hand operand only if the left-hand operand evaluates to null.