CKTIS / C#
C# — `#nullable enable`, `string?`, and `[NotNullWhen(true)]` for two `out` parameters
Enable nullable analysis and describe both outputs of a `Try*` method so the compiler knows that neither output is null on success.
Version: C# 12 and .NET 8; later runtimes may add compatible features
Syntax
#nullable enable
using System.Diagnostics.CodeAnalysis;
static bool TryGetLabels(
string key,
[NotNullWhen(true)] out string? primary,
[NotNullWhen(true)] out string? secondary)In C# 12 on .NET 8, #nullable enable turns on nullable annotations and warnings for the following lines until another directive changes the context or the file ends. string? allows null; string declares a reference that should not be null. They have the same runtime type, and the annotation adds no runtime check.
[NotNullWhen(true)] is the short form of the attribute NotNullWhenAttribute from System.Diagnostics.CodeAnalysis. On an out string? parameter it means that if the method returns true, that particular output is not null. The guarantee applies only to the annotated parameter, so TryGetLabels annotates primary and secondary separately.
The method must assign both out parameters before every normal return. For "menu", this implementation supplies "Open" and "Close" and returns true. For another key, it assigns null to both and returns false. That's an implementation choice: the attribute doesn't say that either output must be null when the return value is false.
In the if branch, the compiler treats both references as not null, so you can read both Length properties without !. In else, both are treated as possibly null; ?? supplies fallback text. The attribute doesn't enforce the contract at runtime. By contrast, [MaybeNull] allows a possibly null output despite a non-nullable declaration, while [MemberNotNull] describes the state of named fields or properties after a method returns, not out parameters.
Examples
#nullable enable
using System;
using System.Diagnostics.CodeAnalysis;
foreach (string key in new[] { "menu", "other" })
{
if (TryGetLabels(key, out string? primary, out string? secondary))
{
Console.WriteLine($"{primary.Length}, {secondary.Length}");
}
else
{
Console.WriteLine($"{primary ?? "<null>"}, {secondary ?? "<null>"}");
}
}
static bool TryGetLabels(
string key,
[NotNullWhen(true)] out string? primary,
[NotNullWhen(true)] out string? secondary)
{
if (key == "menu")
{
primary = "Open";
secondary = "Close";
return true;
}
primary = null;
secondary = null;
return false;
}Result
4, 5 <null>, <null>
The first line contains the lengths of both labels; the second shows both null markers. Remove the attribute from `secondary` alone and rebuild: expect CS8602 at `secondary.Length`, but not at `primary.Length`.
Related lessons
- C# · Lesson 53 · Advanced · Version: 3