Although C# 8 is released for a while, I’m still discovering new features.
When I want to conditionally assign a value to a variable whether it is null or not, I typically used either the conditional ternary operator:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
List<string> productNames=null; | |
productNames=productNames==null?new List<string>(): productNames; |
or a coalesce expression:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
List<string> productNames = null; | |
productNames = productNames ?? new List<string>(); |
With C# 8, you can even write this shorter with the null coalescing operator:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
List<string> productNames = null; | |
productNames ??= new List<string>(); |