CKTIS / C#
NotNullWhenAttribute — a conditional non-null guarantee
NotNullWhenAttribute describes the relationship between a method's bool result and an argument's null-state. It lets nullable analysis recognize the safe branch after a checking method or a Try*-style method, without using the ! operator.
Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification
Syntax
bool Method([NotNullWhen(true)] string? value)
bool TryMethod([NotNullWhen(true)] out string? value)
bool IsMissing([NotNullWhen(false)] string? value)NotNullWhenAttribute in System.Diagnostics.CodeAnalysis is a parameter attribute describing a conditional postcondition. [NotNullWhen(true)] means that after the method returns normally with true, the argument is not null, even though its type permits it. The abbreviated attribute name is NotNullWhen; its constructor accepts a bool, and its ReturnValue property exposes that value.
Apply the attribute to parameters, including out and ref parameters, not to the return value. [NotNullWhen(false)] moves the guarantee to the false result. The opposite result does not itself mean the argument is null: the attribute leaves its state unspecified in that branch.
Enable nullable analysis, for example with #nullable enable. In the example, TryGetName guarantees a non-null out value when it returns true, so name.Length needs no ! operator. The attribute itself neither checks values at runtime nor changes them; the implementation must honor the contract.
The API is available in the .NET 10 target environment. The repository setting LangVersion=preview does not mean this attribute is an experimental feature.
Examples
#nullable enable
using System;
using System.Diagnostics.CodeAnalysis;
internal static class Program
{
private static bool TryGetName(int id, [NotNullWhen(true)] out string? name)
{
name = id == 1 ? "Ada" : null;
return name is not null;
}
private static void Main()
{
foreach (int id in new[] { 1, 2 })
{
if (TryGetName(id, out string? name))
Console.WriteLine(name.Length);
else
Console.WriteLine("missing");
}
}
}Result
3 missing
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.