Null Coalescing Operator in C#: What It Is and How to Use
null coalescing operator (??) in C# returns the left-hand operand if it is not null; otherwise, it returns the right-hand operand. It is a simple way to provide a default value when dealing with nullable types or references.How It Works
Imagine you have a box that might be empty (null) or might contain something. The null coalescing operator checks the box on the left side first. If the box has something inside (not null), it takes that. If the box is empty (null), it takes the item from the right side instead.
This operator helps avoid extra checks like "if this is null, then do that" by combining the check and the fallback in one simple step. It works with nullable types and reference types, making your code cleaner and easier to read.
Example
This example shows how to use the null coalescing operator to provide a default name if the original name is null.
string? name = null; string displayName = name ?? "Guest"; Console.WriteLine(displayName);
When to Use
Use the null coalescing operator when you want to assign a default value if a variable might be null. This is common when reading user input, working with optional data, or handling nullable database fields.
For example, if you get a user's nickname but it might be missing, you can use ?? to show a fallback name instead of dealing with null checks everywhere.
Key Points
- The operator is written as
??. - It returns the left value if not null; otherwise, the right value.
- It simplifies code by reducing explicit null checks.
- Works with nullable and reference types.