C#•Operators
C# Operators: Null-Conditional (?.) and Null-Coalescing (??)
Learn modern C# null-safety operators (?? and ?.) to eliminate NullReferenceException crashes.
Syntax
string val = nullableObj?.Property ?? "Default";
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| ?. | Null-Conditional | Accesses property only if object is non-null; otherwise returns null. |
| ?? | Null-Coalescing | Returns right operand if left operand is null. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing C# locally:
using System;
public class Program {
public static void Main() {
string configuredHost = null;
// Null-coalescing fallback
string host = configuredHost ?? "127.0.0.1";
int port = 8080;
Console.WriteLine($"Server Host: {host}:{port}");
// Compound assignment with null-coalescing ??=
string cacheKey = null;
cacheKey ??= "DEFAULT_KEY";
Console.WriteLine($"Cache Key: {cacheKey}");
}
}Expected Output:
Server Host: 127.0.0.1:8080 Cache Key: DEFAULT_KEY
How It Works: Step-by-Step
- Lines 5-7: configuredHost ?? "127.0.0.1" provides default fallback.
- Lines 12-14: ??= assigns only if cacheKey is currently null.
Key Concepts
- ?? returns the fallback value only when left-hand operand evaluates to null.
- ??= assigns only if the variable is currently null.
Common Mistake: Dereferencing null without ?. operator
Accessing properties on null throws NullReferenceException. Use obj?.Property.
❌ Incorrect
string s = null; int len = s.Length; // Throws NullReferenceException!
✅ Correct
string s = null; int? len = s?.Length; // Evaluates safely to null
Related C# Tutorials & Compiler
C# Strongly Typed Implicit Var Assignments and Data Types
Master C# static typing with implicit var inference, primitive types (int, double, decimal, bool), and formatting specifiers.
C# Type Casting: int.TryParse, as, and is Pattern Matching
Safely parse strings and cast objects using int.TryParse, as operator, and is pattern matching.
C# Pattern Matching Switch Statements and Expressions
Implement modern C# pattern matching switch expressions (=>) with relational ranges, logical combinators (and/or), and discard guards.
C# Online Compiler
Open in Compilra IDE
Run and test C# on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.