Operators, Null-Coalescing (??, ??=) & Null-Forgiving Operator (!)
1Concept
C# offers expressive null-safe operators: null-coalescing ?? (fallback if null), null-coalescing assignment ??= (assigns only if current value is null), null-conditional ?. (short-circuits to null if target is null), and null-forgiving !.
2Architecture Diagram
val = input ?? "Default"; // If input is null, returns "Default" input ??= "Fallback"; // If input is null, assigns "Fallback" to input length = user?.Name?.Length; // Returns int? without throwing NullReferenceException
3Code Example
Stage 0 Language Foundations
using System;
class Program
{
static void Main()
{
string? candidateName = null;
// Null-coalescing fallback
string displayName = candidateName ?? "Anonymous Candidate";
Console.WriteLine($"Display: {displayName}");
// Null-coalescing assignment
candidateName ??= "Alex Johnson";
Console.WriteLine($"CandidateName after ??=: {candidateName}");
// Null-conditional
string? nullableString = "CareerAI";
int? len = nullableString?.Length;
Console.WriteLine($"Length via ?.: {len}");
}
}4Expected Output
Display: Anonymous Candidate CandidateName after ??=: Alex Johnson Length via ?.: 8
5Key Takeaways
- ✓Use ??= for lazy initialization of caching dictionaries or properties.
- ✓?. safely stops navigation if any link in the chain is null.
- ✓Never overuse the null-forgiving operator (!) unless you have proven non-null invariant.