C# > Core C# > Operators and Expressions > Null-coalescing Operator (??)

Using the Null-Coalescing Operator (??) for Default Values

This snippet demonstrates how to use the null-coalescing operator (??) in C# to provide a default value when a nullable variable is null. It's a concise way to handle nulls and avoid NullReferenceException errors.

Basic Usage

In this example, the name variable is initially null. The ?? operator checks if name is null. Since it is, the operator returns the default value, which is "Guest". This value is then assigned to the displayName variable.

string name = null;
string displayName = name ?? "Guest";

Console.WriteLine("Display Name: " + displayName); // Output: Display Name: Guest

Understanding the Operator

The null-coalescing operator (??) takes two operands. If the left-hand operand is not null, it returns the left-hand operand. Otherwise, it returns the right-hand operand. This operator is particularly useful when working with nullable value types or reference types where null is a possibility.

Nullable Value Types

This example shows how the operator works with nullable value types (int?). If nullableAge is null, the operator returns 0, ensuring that the age variable has a valid integer value.

int? nullableAge = null;
int age = nullableAge ?? 0;

Console.WriteLine("Age: " + age); // Output: Age: 0

Chaining the Operator

The ?? operator can be chained to provide a fallback mechanism. The code checks if address is null, then if city is null. If both are null, it returns "Unknown Location".

string address = null;
string city = null;
string location = address ?? city ?? "Unknown Location";

Console.WriteLine("Location: " + location); // Output: Location: Unknown Location

Real-Life Use Case Section

Imagine reading configuration settings from a file. If a specific setting is missing or invalid (resulting in a null value), you can use the ?? operator to provide a default configuration value. This prevents your application from crashing due to a missing configuration.

Best Practices

Use the ?? operator to provide sensible defaults. This improves code readability and reduces the risk of NullReferenceException errors. Avoid overusing it in complex chains where the logic becomes difficult to follow; consider using if/else statements for more complex scenarios.

Interview Tip

Be prepared to explain how the null-coalescing operator works, its benefits, and potential use cases. Understand the difference between ?? and the null-conditional operator (?.). The ?? provides a default value if the expression is null. The ?. is used to safely access members of potentially null objects, avoiding NullReferenceException errors, and returning null if the left operand is null.

When to use them

Use the null-coalescing operator when you need a concise way to provide a default value for a variable that might be null. This is particularly useful for simplifying null checks and reducing code verbosity.

Alternatives

The alternative to using the ?? operator is to use a traditional if statement to check for null. For example, instead of string displayName = name ?? "Guest"; you could write: string displayName; if (name == null) { displayName = "Guest"; } else { displayName = name; }. The ?? operator provides a more concise way to achieve the same result.

Pros

?? operator provides:Conciseness: Reduces code verbosity compared to traditional null checks (if statements). Readability: Improves code readability by clearly expressing the intent to provide a default value. Prevents NullReferenceException errors by ensuring a valid value is always assigned.

Cons

Overuse in complex scenarios can reduce readability. It's best used for simple null checks and default value assignments. For more complex logic, consider using if statements or other control flow structures.

FAQ

  • What happens if both operands of the ?? operator are null?

    If the left-hand operand is null and the right-hand operand is also null, the operator will return null. This is the only case where the operator will return null.
  • Can I use the ?? operator with value types?

    Yes, but you typically use it with nullable value types (e.g., int?, bool?). Without the nullable type, the value type cannot be null, so the operator wouldn't have any effect.
  • How is the null-coalescing operator different from the null-conditional operator (?. )?

    The null-conditional operator (?.) is used to safely access members of a potentially null object. It returns null if the object is null, preventing a NullReferenceException. The null-coalescing operator (??) provides a default value when an expression is null. They are used for different purposes but can often be used together.