In C#, how do [NotNull] and [DoesNotReturn] let a team's own null-guard helper remove nullable warnings at its call sites?
answer
- a postcondition on an input
- null may go in, not come out
- a helper that always throws
- Debug.Assert's bool parameter
basics
~20 sDeclare the guard's parameter [NotNull] object? value: callers may pass null, but once the call returns the argument is not-null. Mark an always-throwing helper [DoesNotReturn] so nullable analysis treats code after its call as unreachable.
solid answer
~40 sA guard such as `Guard.NotNull(object? value, string name)` that throws on null still leaves the caller's variable maybe-null, because the compiler never looks inside the guard, so the next `region.Length` gets CS8602. Declaring the parameter `[NotNull] object? value` keeps null legal as an input but promises that, if the call returns normally, the argument is not-null; the compiler holds the guard to it and reports CS8777 when a path can exit with `value` still null. A throw helper called as `if (value is null) Throw(name);` needs `[DoesNotReturn]`, so nullable analysis treats the rest of that branch as unreachable; a `[DoesNotReturn]` method that can return gets CS8763. `[DoesNotReturnIf(false)]` on a `bool` parameter, as on `Debug.Assert`, does the same conditionally.
code
csharp · 23 linesusing System.Diagnostics.CodeAnalysis;
Console.WriteLine(Describe("orders"));
try { Console.WriteLine(Describe(null)); }
catch (ArgumentNullException ex) { Console.WriteLine($"rejected: {ex.ParamName}"); }
static string Describe(string? region)
{
Guard.NotNull(region, nameof(region));
return $"{region.ToUpperInvariant()} ({region.Length})"; // no CS8602
}
static class Guard
{
public static void NotNull([NotNull] object? value, string name)
{
if (value is null)
Throw(name);
} // without [DoesNotReturn] on Throw, CS8777 is reported here
[DoesNotReturn]
private static void Throw(string name) => throw new ArgumentNullException(name);
}go deeper
Recall that ArgumentNullException.ThrowIfNull removes warnings because its parameter is [NotNull] object?, and that your own guard needs the same attribute.
Explain preconditions versus postconditions, why [NotNull] goes on a nullable parameter, and how [DoesNotReturn] prunes the null path after a throw helper.
Mention CS8777 and CS8763 as the compiler's checks, the definite-assignment gap, and the Debug.Assert Release-build trap when reviewing guard code.
Decide whether a team keeps its own guard library at all once the BCL helpers exist, and require any kept helper to carry accurate attributes.
## The problem with home-grown guards Many codebases have a small `Guard` class written before nullable reference types existed: ```csharp public static void NotNull(object? value, string name) { if (value is null) throw new ArgumentNullException(name); } ``` After `Guard.NotNull(region, nameof(region));` the caller still gets **CS8602** on `region.Length`. Nullable analysis judges a call by the callee's signature alone, and nothing in `NotNull(object? value, string name)` says that returning normally means the argument was checked. The guard works at run time, but the compiler cannot know. ## [NotNull]: a postcondition on an input The nullable analysis attributes split into **preconditions**, which describe what may go in, and **postconditions**, which describe what is true afterwards. A guard needs a postcondition: | Declaration | Callers may pass a maybe-null value? | State of the argument after the call | |---|---|---| | `object value` | no, CS8604 at the call | not-null, once that warning is reported | | `[DisallowNull] object? value` | no, CS8604 at the call | not-null, once that warning is reported | | `[AllowNull] object value` | yes | unchanged, still maybe-null | | `[NotNull] object? value` | yes | **not-null** | The first two rows push the warning onto the very call that was meant to perform the check, which defeats the guard. `[NotNull] object? value` is the honest contract: null is an allowed input, and a normal return proves the argument was not null. `ArgumentNullException.ThrowIfNull` in the BCL is declared exactly this way, with `[NotNull] object? argument`. The compiler checks the guard itself: if any path can leave the method while `value` may still be null, it reports **CS8777** ("Parameter 'value' must have a non-null value when exiting."). ## [DoesNotReturn] for throw helpers Teams often move the `throw` into a separate method so that guards stay one line long: ```csharp public static void NotNull([NotNull] object? value, string name) { if (value is null) Throw(name); } [DoesNotReturn] private static void Throw(string name) => throw new ArgumentNullException(name); ``` Without `[DoesNotReturn]`, the analysis assumes `Throw(name)` may return, so `value` could still be null at the closing brace and `NotNull` gets CS8777. With it, the compiler treats the code after the call as **unreachable for nullable analysis**, the null path ends there, and the warning goes away. The same applies at any call site: `if (order is null) Fail("order");` followed by `order.Id` is clean when `Fail` is marked. The attribute is checked too: a `[DoesNotReturn]` method whose end can be reached reports **CS8763** ("A method marked [DoesNotReturn] should not return."). It targets **methods** only. ## [DoesNotReturnIf] for assertion-style helpers Some helpers stop only for one value of a `bool` argument. `[DoesNotReturnIf(false)]` on that parameter says: when the argument is `false`, this call does not return. `Debug.Assert(bool condition)` is declared with `[DoesNotReturnIf(false)] bool condition`, so after `Debug.Assert(name is not null);` the compiler treats `name` as not-null. Note the trap: `Debug.Assert` is also marked `[Conditional("DEBUG")]`, so in a Release build the call is removed while the compiler's assumption remains. ## Choosing the attribute for a helper - A guard that **returns normally only for non-null input**: `[NotNull]` on the nullable parameter. - A helper that **always throws**: `[DoesNotReturn]` on the method. - A helper that **stops for one `bool` value**: `[DoesNotReturnIf(false)]` or `[DoesNotReturnIf(true)]` on that parameter. - A helper that **only reports**, returning a `bool` such as `IsMissing(string?)`: `[NotNullWhen(false)]` on the parameter instead. - A guard that **returns its argument**, such as `T Ensure<T>([NotNull] T? value)`, so callers can write `var r = Ensure(region);`. ## What the attributes do not do - **No run-time effect.** The throw happens because your code throws; the attributes only describe that behaviour to the compiler. - **Nullable analysis only.** Definite assignment ignores `[DoesNotReturn]`: a local assigned on one branch, with a call to a `[DoesNotReturn]` static method declared on a class on the other branch, still gets **CS0165** when it is read. Use a `throw` statement on that path when definite assignment matters. - **Callers compiled with nullable disabled** see no warnings either way. Which guard helpers to write, and when `ArgumentNullException.ThrowIfNull` is enough, is covered with throwing and catching exceptions; this question is about making a guard you already have speak to the compiler.
- Why [NotNull] object? rather than a non-nullable object parameter?A non-nullable parameter is a precondition, so a caller passing a maybe-null variable gets CS8604 at the guard call itself, which is the call meant to perform the check. `[NotNull] object?` accepts the maybe-null argument and makes it not-null afterwards, which is exactly the guard's contract.
- Does [DoesNotReturn] also satisfy definite assignment?No. It feeds nullable analysis only. If a local is assigned on one branch and the other branch calls a `[DoesNotReturn]` static method declared on a class, reading the local afterwards still reports CS0165. A `throw` statement on that path satisfies both analyses.
- Why can Debug.Assert(x is not null) be misleading in a Release build?`Debug.Assert` declares `[DoesNotReturnIf(false)] bool condition`, so the compiler treats `x` as not-null afterwards. But the method is also `[Conditional("DEBUG")]`, so a Release build removes the call. The analysis is the same in both builds, while the check only exists in Debug.
A security desk at an office entrance: anyone may walk up, including someone without a badge, but everyone who gets past the desk has been checked. [NotNull] on a guard's parameter describes the people past the desk, not the queue in front of it.
- [NotNull] on a parameter makes the runtime reject null arguments.
- The throw inside the guard is enough; the compiler sees it at the call site.
- [DisallowNull] is the right attribute for a guard's input parameter.
- [DoesNotReturn] fits any helper that usually throws.
- Making the guard's parameter non-nullable object fixes the caller's warning.