Last active
July 14, 2023 11:44
-
-
Save a-patel/4b63834276158e59cb6923c824382ece to your computer and use it in GitHub Desktop.
C#.NET - Null Coalescing Assignment Operator (??=) Example
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
/* Example-1 */ | |
// Without null coalescing assignment operator | |
string name = null; | |
if (name == null) | |
{ | |
name = "Unknown"; | |
} | |
// With null coalescing assignment operator | |
string name ??= "Unknown"; | |
/* Example-2 */ | |
// Without null coalescing assignment operator | |
user.Country = user.Country != null ? user.Country : "US"; | |
// With null coalescing assignment operator | |
user.Country ??= "US"; | |
/* Example-3 - General usage */ | |
// Without null coalescing assignment operator | |
if (variable is null) | |
{ | |
variable = expression; | |
} | |
// With null coalescing assignment operator | |
variable ??= expression; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment