Skip to content

Instantly share code, notes, and snippets.

@a-patel
Last active July 14, 2023 11:44
Show Gist options
  • Save a-patel/4b63834276158e59cb6923c824382ece to your computer and use it in GitHub Desktop.
Save a-patel/4b63834276158e59cb6923c824382ece to your computer and use it in GitHub Desktop.
C#.NET - Null Coalescing Assignment Operator (??=) Example
/* 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