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

≯℡__Kan透↙ 提交于 2020-02-25 13:15:53

问题


With the new C# 8 capabilities is there a short cut now for this code structure:

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

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/59300159/short-cut-for-a-check-for-null-and-assigning-a-value-to-it-if-it-is

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!