Skip to content

Instantly share code, notes, and snippets.

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