What do two question marks together mean in C#?
The ??
in C# is called the null-coalescing operator. It’s used to provide a default value when the left-hand operand is null
. This operator helps you simplify code that would otherwise require explicit null checks.
How It Works
string message = null; string defaultMessage = "Hello World"; string result = message ?? defaultMessage; Console.WriteLine(result); // Outputs "Hello World"
- Left operand: The value that might be
null
. - Right operand: The fallback (or “coalesced”) value that will be used if the left operand is
null
.
Common Use Cases
-
Setting Defaults
When you have a nullable reference type or a nullable value type, the null-coalescing operator lets you provide a default without an explicitif
statement. -
Parameter and Configuration Values
If a parameter or configuration is optional, you can check and assign a default more concisely. -
Chaining with Null-Conditional Operators
Often used with the?.
(null-conditional) operator to handle deeply nested objects or properties without lengthy null checks.
Avoiding Over-Engineering
Sometimes developers place too many default checks using ??
, which can obscure the code’s intent. Use it wisely to maintain readability and clarity.
Strengthen Your C# Skills
To improve your C# fundamentals and learn practical coding patterns, consider these in-depth courses at DesignGurus.io:
- Grokking the Coding Interview: Patterns for Coding Questions
- Grokking Data Structures & Algorithms for Coding Interviews
You can also explore the DesignGurus.io YouTube channel for free tutorials and discussions about coding, interviews, and system design.