With nullable reference types enabled, how do you annotate a C# cache's TryGetValue out parameter so callers get no warning after a true result?
answer
- the bool result carries the null-state
- nullable type plus a conditional promise
- a stored null can be a hit
- what Dictionary<TKey,TValue> declares
basics
~10 sDeclare it [NotNullWhen(true)] out string? value: after a true return the value is not-null, after false maybe-null. For a generic TValue use [MaybeNullWhen(false)] out TValue value, as Dictionary<TKey,TValue>.TryGetValue does.
solid answer
~40 sFor a concrete type I write `bool TryGetValue(string key, [NotNullWhen(true)] out string? value)`. The `string?` lets the method assign `null` on a miss, and the attribute tells the compiler that a `true` result means the value is not-null, so `if (cache.TryGetValue(k, out var v)) v.Length` compiles cleanly while using `v` on the `false` path gets CS8602. The compiler checks the body too: returning `true` while `value` may be null reports CS8762. For a generic cache I follow `Dictionary<TKey,TValue>.TryGetValue` and write `[MaybeNullWhen(false)] out TValue value`, because when `TValue` is itself nullable a stored `null` is a legitimate hit and must not be promised away. None of this exists at run time; it only shapes warnings.
code
csharp · 26 linesusing System.Diagnostics.CodeAnalysis;
var cache = new SessionCache();
cache.Set("u1", "Ada");
if (cache.TryGetValue("u1", out string? name))
Console.WriteLine($"hit: {name.Length} chars"); // not-null after true
Console.WriteLine(cache.TryGetValue("u2", out var other) ? other.ToUpper() : "u2 not cached");
class SessionCache
{
private readonly Dictionary<string, string> _items = new();
public void Set(string key, string value) => _items[key] = value;
public bool TryGetValue(string key, [NotNullWhen(true)] out string? value)
{
if (_items.TryGetValue(key, out var found))
{
value = found;
return true;
}
value = null;
return false;
}
}go deeper
Know the Try shape: a bool result, an out value, and that a true result should let you use the value without a null check.
Explain how the bool result carries the out argument's null-state, why the parameter is string?, and why only the false path warns.
Show why Dictionary uses [MaybeNullWhen(false)] out TValue and why NotNullWhen(true) on TValue? breaks when a stored null is a hit.
Treat these annotations as part of a public API: changing one changes the warnings every consumer compiles with, so review them like signature changes.
## The Try pattern and its null problem A **Try method** returns a `bool` for success and hands the result back through an `out` parameter: `bool TryGetValue(string key, out string value)`. On a miss the method must still assign the `out` parameter, and the natural value is `null`. With **nullable reference types** enabled, every plain spelling of the signature goes wrong somewhere: | Signature | Inside the method | At the call site | |---|---|---| | `out string value` | `value = null;` warns CS8625 ("Cannot convert null literal to non-nullable reference type.") | the value looks not-null even after a miss | | `out string? value` | `value = null;` is fine | `v.Length` warns CS8602 even after `true` | | `[NotNullWhen(true)] out string? value` | `value = null;` is fine on the miss path | not-null after `true`, maybe-null after `false` | The last row is what the attribute is for: the **null-state of the out argument depends on the return value**, and only an attribute can say so. ## [NotNullWhen(true)] on a nullable out parameter ```csharp public bool TryGetValue(string key, [NotNullWhen(true)] out string? value) { if (_items.TryGetValue(key, out var found)) { value = found; return true; } value = null; return false; } ``` At a call site the compiler splits the state on the result: - `if (cache.TryGetValue(k, out var v)) Console.WriteLine(v.Length);` compiles without a warning. - `if (!cache.TryGetValue(k, out var v)) Console.WriteLine(v.Length);` reports **CS8602**, because on the `false` path `v` is maybe-null. - `if (!cache.TryGetValue(k, out var v)) return;` followed by `v.Length` compiles cleanly: the only path that reaches the dereference is the `true` one. - `cache.TryGetValue(k, out var v) && v.Length > 0` is also clean, because `&&` evaluates the right side only after `true`. The attribute comes from `System.Diagnostics.CodeAnalysis`, applies to **parameters only**, and changes nothing in the compiled IL. ## The compiler checks the method as well For `out` and `ref` parameters the promise is enforced in the body. Writing `value = null; return true;` reports **CS8762** ("Parameter 'value' must have a non-null value when exiting with 'true'."). So a careless refactoring of the method is caught where it happens, not in some caller later. ## Generic values: [MaybeNullWhen(false)] A generic cache is different, because `TValue` might be a nullable type itself. `Dictionary<TKey,TValue>.TryGetValue` is declared as: ```csharp public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) ``` Read it from the other side: the type is `TValue` as given, and **only when the result is `false`** may the value be null even if `TValue` is non-nullable. Consequences: 1. With `Cache<string>`, a `true` result yields a not-null `string`; a `false` result yields maybe-null. 2. With `Cache<string?>`, a `true` result yields `string?`, which is honest: a stored `null` is a real hit. 3. With `Cache<int>`, the value is a plain `int`, and a miss leaves `default(int)`. The tempting alternative, `[NotNullWhen(true)] out TValue? value`, claims too much. When `TValue` is `string?` and the cache holds a null, the method returns `true` with `value` null; the compiler reports CS8762 in the implementation, and if that warning is suppressed every caller is told a null is not-null. Without any attribute, `out TValue value` with `value = default;` reports CS8601 ("Possible null reference assignment."). ## A checklist for Try methods 1. Concrete reference type: `[NotNullWhen(true)] out T? value`. 2. Generic or non-nullable declared type: `[MaybeNullWhen(false)] out T value`. 3. Never annotate `[NotNull]` on a Try out parameter: it is unconditional, and a miss breaks it. 4. Let the compiler's CS8762 and CS8601 guide the body; do not silence them with `!`. 5. At the call site, `out var v` takes its type from the declaration, so `v` is `string?` and the attribute alone decides where it may be dereferenced. The same reasoning applies to `ref` parameters, which the compiler checks the same way, and to interfaces: an implementation whose annotations promise less than the interface member (for example, dropping `[NotNullWhen(true)]`) gets a nullability-mismatch warning such as CS8767, so annotate the interface first and let implementations follow. Whether a missing key should be a `false` result or an exception is a design question covered with exception design; how dictionaries behave on a miss is covered with dictionaries. This question is only about telling the compiler what the `bool` means.
- For a non-generic cache, is [MaybeNullWhen(false)] out string value the same as [NotNullWhen(true)] out string? value?For callers, yes: not-null after `true`, maybe-null after `false`. Inside the method both let you assign `null` on the miss path without a warning, and both report CS8762 if you return `true` with `value` null. The usual convention is `NotNullWhen` on a nullable type and `MaybeNullWhen` on a non-nullable or generic type.
- Why not [NotNullWhen(true)] out TValue? on the generic cache?Because with `TValue = string?` a cached null is a real hit: the method returns `true` with `value` null. The compiler flags that body with CS8762, and if someone suppresses it, callers are told a null value is not-null. `[MaybeNullWhen(false)] out TValue` promises only what holds for every type argument, which is why `Dictionary<TKey,TValue>` uses it.
- Does if (!cache.TryGetValue(k, out var v)) return; protect the code after it?Yes. The analysis follows the negation: inside the early-return branch `v` is maybe-null, and the only path that continues past the `if` is the one where the call returned `true`, so `v.Length` below the guard compiles without a warning.
- Declare the out parameter as non-nullable string and assign null on a miss.
- [NotNullWhen(false)] is the right attribute for a Try method's out value.
- The attribute makes TryGetValue throw if it returns true with a null value.
- [NotNullWhen(true)] out TValue? means the same as Dictionary's annotation.
- Callers still need value! after a true result from an annotated Try method.