Phase 3 of 30 · Topic 3.1

Null-Coalescing Assignment (??=) & Conditional Member Access (?.)

1Concept

Null-coalescing (`??`) and null-coalescing assignment (`??=`) assign values only when operands evaluate to null, avoiding expensive re-evaluations and thread contention.

2Architecture Diagram

Expression: target ??= ExpensiveFactory()
       │
   Is target == null?
     ├── YES ──> Compute ExpensiveFactory() & assign to target
     └── NO  ──> Bypass evaluation completely (Zero CPU waste)

3Code Example

C# 13 & .NET 9
using System;
using System.Collections.Generic;

public class NullCoalesceDemo
{
    private static List<string>? _cache;

    public static List<string> GetLazyList()
    {
        // Thread-safe-ready lazy initialization pattern
        return _cache ??= InitializeData();
    }

    private static List<string> InitializeData()
    {
        Console.WriteLine("Initializing expensive cache dataset...");
        return new List<string> { "DotNet9", "CSharp13", "RyuJIT" };
    }

    public static void Main()
    {
        var l1 = GetLazyList();
        var l2 = GetLazyList(); // Bypasses initialization
        Console.WriteLine($"Cache elements count: {l2.Count}");
    }
}

4Expected Output

Initializing expensive cache dataset...
Cache elements count: 3

5Key Takeaways

  • `??=` prevents multiple redundant instantiations.
  • `?.` short-circuits evaluation without throwing `NullReferenceException`.
  • Never use `?.` where `null` represents a critical domain bug that should fail fast.