Last active
July 14, 2023 11:36
-
-
Save a-patel/0034eccb0d87be23b69e5ac1af376e53 to your computer and use it in GitHub Desktop.
C#.NET - Null Coalescing Operator (??) Example
This file contains hidden or 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 operator | |
string name = GetUserName(); | |
if (name == null) | |
{ | |
name = "Unknown"; | |
} | |
// With null coalescing operator | |
string name = GetUserName() ?? "Unknown"; | |
/* Example-2 */ | |
// Without null coalescing operator | |
string country = user.Country != null ? user.Country : "US"; | |
// With null coalescing operator | |
string country = user.Country ?? "US"; | |
/* Example-3 */ | |
// With null coalescing operator | |
public string Name | |
{ | |
get => name; | |
set => name = value ?? throw new ArgumentNullException(nameof(value), "Name cannot be null"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment