Alan2
Alan2

Reputation: 24592

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();

Upvotes: 2

Views: 768

Answers (2)

Salah Akbari
Salah Akbari

Reputation: 39966

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.

Upvotes: 9

Tolik Pylypchuk
Tolik Pylypchuk

Reputation: 680

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

Upvotes: 4

Related Questions