C#:C# Operators: Null-Conditional (?.) and Null-Coalescing (??)
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:

ParameterTypeDescription
?.Null-ConditionalAccesses property only if object is non-null; otherwise returns null.
??Null-CoalescingReturns right operand if left operand is null.

Ready-to-Run Code Example

Executable in Compilra

Run 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

Run and test C# on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C# Online Compiler