In C#, when do `??` and `??=` evaluate their right-hand operand, and what does `_avatars ??= new AvatarCache()` return?
answer
- lazy right operand
- assigns only on null
- right-associative, low precedence
- non-nullable value type: CS0019
basics
~20 sBoth evaluate the right operand only when the left one is null. _avatars ??= new AvatarCache() constructs and stores a cache on the first call and returns the stored instance on every later call, without constructing again.
solid answer
~40 s`a ?? b` returns `a` if it is not null and only otherwise evaluates `b`. `a ??= b`, added in C# 8, assigns `b` only when `a` is null, does not evaluate `b` at all otherwise, and its value is whatever `a` now holds — which makes `_avatars ??= new AvatarCache()` the idiom for a lazily created field. Both are right-associative, so `a ?? b ?? c` takes the first non-null value, and both bind more loosely than arithmetic: `badges ?? 0 + 1` means `badges ?? (0 + 1)`. A non-nullable value-type left operand is error CS0019. They test for null only, ignore overloaded `==`, and `??=` is not thread-safe.
code
csharp · 26 linesvar page = new ProfilePage();
Console.WriteLine(page.Avatars.Size); // "creating avatar cache" prints once
Console.WriteLine(page.Avatars.Size); // the cached instance is reused
string? nickname = null, fullName = null, email = "[email protected]";
Console.WriteLine(nickname ?? fullName ?? email ?? "guest"); // right-associative
int? width = null;
int used = width ??= 64; // the result of ??= is an int here
Console.WriteLine($"{used} {width}"); // 64 64
int? badges = 5;
Console.WriteLine(badges ?? 0 + 1); // 5: parsed as badges ?? (0 + 1)
Console.WriteLine((badges ?? 0) + 1); // 6
class AvatarCache
{
public AvatarCache() => Console.WriteLine("creating avatar cache");
public int Size => 128;
}
class ProfilePage
{
private AvatarCache? _avatars;
public AvatarCache Avatars => _avatars ??= new AvatarCache();
}go deeper
Recall that a ?? b gives b only when a is null, and that ??= fills in a value only when the variable is null.
Explain that the right operand is evaluated lazily, why ??= suits lazy fields, the right associativity and the low precedence.
Spot the precedence bug in arithmetic with ??, and the race in ??= lazy initialization on shared objects.
Set a team rule for lazy fields: ??= on single-threaded paths, Lazy<T> where construction must happen exactly once.
## The two operators - **`a ?? b`**, the null-coalescing operator, returns `a` when `a` is not null. Only when `a` is null does it **evaluate** `b` and return that. The right operand is not computed in advance. - **`a ??= b`**, the null-coalescing assignment operator (C# 8), assigns `b` to `a` only when `a` is null. When `a` already holds a value, `b` is **not evaluated** and nothing is assigned. The expression's value is the value `a` ends up holding. That evaluation rule is what makes `??=` the idiom for lazy initialization: ```csharp private AvatarCache? _avatars; public AvatarCache Avatars => _avatars ??= new AvatarCache(); ``` The first read constructs the cache, stores it in the field and returns it. Every later read finds the field non-null, skips `new AvatarCache()` entirely and returns the stored instance. It replaces the longer `if (_avatars is null) _avatars = new AvatarCache(); return _avatars;`. The left operand of `??=` can also be a property or an indexer element. Then the getter runs first, and the setter runs only when the getter returned null. That ordering bites with `Dictionary<TKey, TValue>`: `cache["ada"] ??= Load("ada");` reads the indexer first, and the indexer getter throws `KeyNotFoundException` for a missing key, so `??=` is no substitute for `TryGetValue` there. It works only for keys that exist with a null value. ## Types of the result | Left operand | Right operand | Result type | |---|---|---| | `string?` | `string` | `string` | | `int?` | `int` | `int` (the underlying type) | | `int?` | `int?` | `int?` | | `int` (non-nullable) | anything | error CS0019 | So `int used = width ??= 64;` compiles when `width` is `int?`: the result of `??=` is the underlying `int`. A left operand of a non-nullable value type is rejected, because it can never be null: `int visits = 0; visits ??= 1;` reports error CS0019, "Operator '??=' cannot be applied to operands of type 'int' and 'int'". Operands that do not share a type fail the same way: `string? s; s ?? 5` is CS0019. The left side of `??=` must also be something assignable — a variable, property or indexer element — or the compiler reports CS0131. Since C# 8 the operands may be unconstrained type parameters. ## Associativity and precedence Both operators are **right-associative**: `a ?? b ?? c` means `a ?? (b ?? c)`, so the first non-null value wins, left to right, and evaluation stops there. That makes fallback chains such as `nickname ?? fullName ?? email ?? "guest"` read naturally. Precedence is the trap. `??` binds **more loosely** than arithmetic, comparison and even `||`, and the precedence table ranks only the conditional operator `?:`, assignment and lambda declaration below it. Therefore: 1. `badges ?? 0 + 1` parses as `badges ?? (0 + 1)`, which is `5` when `badges` is `5`, not `6`. 2. `(badges ?? 0) + 1` is the expression the author usually meant. 3. When in doubt, parenthesize the `??` expression. ## `??` with a throw expression The right operand may be a `throw` expression, which turns a null check plus assignment into one line: ```csharp public string UserId { get; } = userId ?? throw new ArgumentNullException(nameof(userId)); ``` The throw runs only when `userId` is null. For plain parameter validation the BCL's guard helpers are covered with exception handling; `?? throw` remains useful when the checked value is assigned or returned at the same time. ## What `??` and `??=` do not do - They test for **null only**. `0`, `false`, an empty string and an empty collection are values, so `"" ?? "guest"` is `""`. - They cannot be overloaded, and they ignore a type's overloaded `==`: the test is a real null test. - `??=` is **not atomic**. Two threads reading `Avatars` at once can both see null and both construct a cache; one assignment wins. When construction must happen once, the tools are `Lazy<T>` or an interlocked compare-exchange, covered with locks and atomics. ## Interview checklist - Right operand evaluated only when needed. - `??=` assigns only on null and returns the resulting value. - Right-associative; lower precedence than `+` and comparisons. - CS0019 for a non-nullable value-type left operand.
- Is `_avatars ??= new AvatarCache()` safe when two threads read the property at once?No. `??=` is a read, a test and a write with nothing atomic about them. Both threads can see null, both construct a cache and one assignment overwrites the other, so callers may hold different instances. If construction must happen exactly once, use `Lazy<T>` or `Interlocked.CompareExchange`.
- What does `nickname ?? fullName ?? "guest"` evaluate when `nickname` is non-null?It returns `nickname` and evaluates nothing else. The operators are right-associative, `nickname ?? (fullName ?? "guest")`, and the right operand of the outer `??` is evaluated only when `nickname` is null, so `fullName` is not even read.
- a ?? b evaluates b first and then picks one of the two values
- ??= overwrites the field on every call
- ?? treats 0, false and empty strings as missing
- badges ?? 0 + 1 adds one to whichever value is chosen
- ??= makes lazy initialization thread-safe