With nullable reference types enabled, why does C# warn after your own IsBlank(string?) check but not after string.IsNullOrWhiteSpace?
answer
- signatures, not method bodies
- an attribute on the BCL parameter
- which bool result proves not-null
- System.Diagnostics.CodeAnalysis
basics
~10 sNullable analysis does not look inside the method you call; it reads the signature. string.IsNullOrWhiteSpace declares [NotNullWhen(false)] string? value, so a false result proves not-null. Your helper needs the same attribute on its parameter.
solid answer
~40 sThe compiler's null-state analysis works one method at a time: at a call site it uses only the callee's declared types plus the attributes from `System.Diagnostics.CodeAnalysis`. The BCL declares `string.IsNullOrWhiteSpace([NotNullWhen(false)] string? value)`, so inside `if (!string.IsNullOrWhiteSpace(key))` the compiler treats `key` as not-null. A team helper `IsBlank(string? s)` runs the same test, but its signature promises nothing, so `key.Length` after `if (!IsBlank(key))` gets CS8602. Declaring `IsBlank([NotNullWhen(false)] string? s)` fixes every caller at once. The attribute is compiler metadata only: nothing extra runs at run time, and for a by-value parameter like this one the compiler does not check that the body keeps the promise.
code
csharp · 20 linesusing System.Diagnostics.CodeAnalysis;
PrintKeyLength(args.Length > 0 ? args[0] : "user:42");
static void PrintKeyLength(string? cacheKey)
{
if (!KeyRules.IsBlank(cacheKey))
Console.WriteLine(cacheKey.Length); // warning CS8602
if (!KeyRules.IsBlankAnnotated(cacheKey))
Console.WriteLine(cacheKey.Length); // no warning
if (!string.IsNullOrWhiteSpace(cacheKey))
Console.WriteLine(cacheKey.Length); // no warning: the BCL method is annotated
}
static class KeyRules
{
public static bool IsBlank(string? s) => s is null || s.Trim().Length == 0;
public static bool IsBlankAnnotated([NotNullWhen(false)] string? s) => s is null || s.Trim().Length == 0;
}go deeper
Recall that the compiler judges a call by its signature, and that string.IsNullOrWhiteSpace carries [NotNullWhen(false)] from System.Diagnostics.CodeAnalysis.
Explain per-method analysis, why the bool in the attribute must match the branch that proves the value usable, and what state the else branch keeps.
Point out that a by-value parameter's promise is not verified, so a buggy helper silently removes warnings; ask for a null test on every annotated helper.
Weigh annotating shared helpers once against scattering ! across callers, and decide whether helper annotations get the same review as public API signatures.
## The symptom A team writes a helper for cache keys that are null, empty or whitespace, and calls it before using the key: ```csharp static bool IsBlank(string? s) => s is null || s.Trim().Length == 0; if (!IsBlank(cacheKey)) Console.WriteLine(cacheKey.Length); // warning CS8602 ``` With **nullable reference types** enabled, the compiler reports **CS8602** ("Dereference of a possibly null reference.") on `cacheKey.Length`. Replace the helper with `string.IsNullOrWhiteSpace(cacheKey)` and the warning disappears, even though both methods perform the same test. ## Why the compiler cannot see your check The compiler tracks a **null-state** for every reference variable: *not-null* or *maybe-null*. That analysis is **per method**: - Inside a method, it follows assignments, `is null` tests, `?.` and branches step by step. - At a **call**, it does not open the callee's body. It reads only the callee's **signature**: parameter types such as `string` vs `string?`, the return type, and any **nullable analysis attributes** applied to them. - After a call to `IsBlank(string? s)`, nothing in the signature links the `bool` result to the argument, so `cacheKey` keeps the state it had before the call: *maybe-null*. It has to work that way: a caller is often compiled against a reference assembly whose method bodies are empty stubs, so the contract must live in metadata. ## What the BCL declares The .NET reference assemblies carry these attributes on the methods everyone already calls: | API | Declared parameter | What a caller learns | |---|---|---| | `string.IsNullOrEmpty` | `[NotNullWhen(false)] string? value` | not-null when the result is `false` | | `string.IsNullOrWhiteSpace` | `[NotNullWhen(false)] string? value` | not-null when the result is `false` | | `Dictionary<TKey,TValue>.TryGetValue` | `[MaybeNullWhen(false)] out TValue value` | maybe-null only when the result is `false` | | `ArgumentNullException.ThrowIfNull` | `[NotNull] object? argument` | not-null once the call returns | That is the whole difference: the framework method states its contract, the team helper does not. ## Annotating the helper Add `using System.Diagnostics.CodeAnalysis;` and put the attribute on the parameter: ```csharp static bool IsBlank([NotNullWhen(false)] string? s) => s is null || s.Trim().Length == 0; ``` Read `[NotNullWhen(false)]` as: **when this method returns `false`, the argument passed for this parameter is not null.** The compiler applies it at every call site: 1. Inside `if (!IsBlank(cacheKey))`, the call returned `false`, so `cacheKey` is *not-null* and `cacheKey.Length` compiles cleanly. 2. In the `else` branch, where the call returned `true`, `cacheKey` keeps the state it had before the call, so it is still *maybe-null*. 3. The parameter stays `string?`, because callers are allowed to pass null: that is the point of a null check. The `bool` in the attribute must match the result that proves the value is usable. A helper shaped like `IsValidKey(string? s)`, which returns `true` for a usable key, takes `[NotNullWhen(true)]` instead. ## What the attribute does not do - **It adds no run-time behaviour.** The attribute is metadata; the IL of `IsBlank` and of its callers is the same with or without it. A null still reaches the method if a caller passes one. - **It is taken on trust for a by-value parameter.** The compiler checks conditional promises on `out` and `ref` parameters (CS8762), but not on a by-value `string?` parameter. If `IsBlank` had a bug and returned `false` for null, no warning would appear anywhere, and callers would meet a `NullReferenceException` at run time. A unit test that passes null to each annotated helper is the safety net. - **It only affects callers compiled with nullable warnings enabled.** Code compiled with nullable disabled sees no warnings either way. ## Related shapes The same idea covers other helper shapes a codebase grows: - **A positive check**, `IsValidKey(string? s)` returning `true` for a usable key: `[NotNullWhen(true)]` on the parameter. - **A transformer** such as `Normalize(string? s)` that returns null only when its input was null: `[return: NotNullIfNotNull(nameof(s))]` on a `string?` return, so `Normalize("a").Length` is clean while `Normalize(maybeNull).Length` still warns. - **A Try method** that hands a value back through an `out` parameter: `[NotNullWhen(true)] out string? value`, where the compiler does check the body. - **A throwing guard**: `[NotNull]` on its parameter, the contract `ArgumentNullException.ThrowIfNull` already uses. In each case the signature is the only thing a caller's compilation sees, so the signature has to say it. The general rules of nullable contexts, the `!` operator and CS8602 itself belong to the material on nullable reference types; the attributes are what let your own methods speak that language.
- What happens if an annotated IsBlank has a bug and returns false for null?Nothing at compile time. For a by-value parameter the compiler trusts `[NotNullWhen(false)]` and does not check the body against it, so the helper compiles cleanly and callers stop warning. The first symptom is a `NullReferenceException` at run time in a caller that dereferenced the value. The compiler only verifies such promises on `out` and `ref` parameters (CS8762).
- Why not just write cacheKey!.Length after the call?The `!` operator silences one warning at one call site, so it has to be repeated at every caller, and it keeps silencing even if the helper later changes. Putting `[NotNullWhen(false)]` on the helper states the contract once, in metadata, and every nullable-enabled caller gets the right state in both branches without suppressions.
- The compiler looks inside IsBlank and sees the null check it performs.
- Nullability attributes add a null check that runs when the method is called.
- IsBlank needs [NotNullWhen(true)] because it returns true for a blank key.
- The only fix is the null-forgiving operator at every call site.
- The compiler always verifies that a helper's body honours [NotNullWhen].