Friday, December 20, 2024

Null Coalescing Operator


C# Null Coalescing Operator (??) is a powerful feature that allows developers to handle null values gracefully by providing a default value.

result = value1 ?? value2;

If value1 is not null, result is value1

If value1 is null, result is value2

Multiple ?? chain operators are used to provide multiple fallback values.

string? first = null;
string? second = null;
string third = "Final Value";

string result = first ?? second ?? third;
Console.WriteLine(result); // Output: "Final Value"

Starting with C# 8.0, the null-coalescing assignment operator (??=) can be used to assign a value to a variable if it is currently null

string? name = null;
name ??= "Default Name";
Console.WriteLine(name); // Output: "Default Name"


Advantages:

  1. Cleaner Code: Reduces the need for explicit if checks for null.
  2. Safe Fallbacks: Ensures default values in case of null.
  3. Improves Readability: Code is more concise and expressive.

No comments:

Post a Comment