C# Reference ยท Reflection, Attributes and Metadata
Nullable analysis attributes
Reference for the nullable analysis attributes in System.Diagnostics.CodeAnalysis: NotNullWhen, MaybeNull, AllowNull, MemberNotNull, DoesNotReturn and more.
With nullable reference types enabled, the compiler tracks whether each reference might be null. It can read the nullability from a signature, but some contracts cannot be written with ? alone: "this out parameter is non-null only when I return true", "this method never returns", "this setter accepts null but the getter never returns it". The attributes in System.Diagnostics.CodeAnalysis describe those contracts so the compiler can follow them without warning you needlessly.
These attributes change only the compiler's flow analysis. They have no effect at runtime and do not add checks. If an attribute makes a promise that your code does not keep, nothing stops you: you will simply get a NullReferenceException where the compiler said it was safe.
using System.Diagnostics.CodeAnalysis; bool TryFind(string key, [NotNullWhen(true)] out string? value);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
[AllowNull] [DisallowNull] [MaybeNull] [NotNull] [MaybeNullWhen(bool)] [NotNullWhen(bool)] [NotNullIfNotNull(string parameterName)] [MemberNotNull(params string[] members)] [MemberNotNullWhen(bool, params string[] members)] [DoesNotReturn] [DoesNotReturnIf(bool)]
| Attribute | Applies to | Meaning |
|---|---|---|
AllowNull |
Input: parameter, property setter, field | The caller may pass null even though the type is non-nullable. |
DisallowNull |
Input | The caller must not pass null even though the type is nullable. |
MaybeNull |
Output: return value, out parameter, getter |
The result may be null even though the type is non-nullable. Typical for T returned from generic code. |
NotNull |
Output, or a ref/out parameter after the call |
The value is non-null when the method returns, even though the type is nullable. |
MaybeNullWhen(b) |
out/ref parameter |
The value may be null when the method returns b. |
NotNullWhen(b) |
Parameter | The value is non-null when the method returns b. |
NotNullIfNotNull(name) |
Return value, ref/out parameter |
The result is non-null if the named parameter's argument is non-null. |
MemberNotNull(...) |
Method, property | The listed fields or properties are non-null after the member returns. |
MemberNotNullWhen(b, ...) |
Method, property | The listed members are non-null when the member returns b. |
DoesNotReturn |
Method | The method never returns normally (it throws or ends the process). |
DoesNotReturnIf(b) |
bool parameter |
The method does not return when the argument equals b. |
Return-value attributes go in the return: target, as in [return: NotNullIfNotNull("x")]. Property attributes control the get and set sides separately: [AllowNull] and [DisallowNull] affect the setter, while [MaybeNull] and [NotNull] affect the getter.
Errors / warnings: the attributes never cause errors. Their effect is that the compiler stops (or starts) issuing warnings such as CS8602 (dereference of a possibly null reference), CS8625 (cannot convert null literal to non-nullable reference type) and CS8618 (non-nullable member not initialized).
Usage notes
NotNullWhenis the workhorse. EveryTryXxxmethod that returns the result in anoutparameter should use it ([NotNullWhen(true)] out string? value). Theouttype stays nullable because it holdsnullwhen the method returnsfalse.MaybeNullWhen(false)is its generic twin. When the type is an unconstrainedT, you cannot writeT?meaningfully for both classes and structs, sobool TryGet(out T value)uses[MaybeNullWhen(false)] out T value.Dictionary<TKey, TValue>.TryGetValueis declared this way.NotNullIfNotNullreplaces overloads. Write one method taking and returningstring?and tell the compiler the result is non-null whenever the argument is, so callers with a non-null argument get a non-null result.MemberNotNullpays off in helper methods. If a constructor calls anInit()method that assigns a field, markInit()so the compiler does not reportCS8618on the constructor.DoesNotReturnends the flow. After a call to such a method the compiler treats the code as unreachable for null analysis, so a check likeif (x is null) Fail();leavesxnon-null afterwards. It does not replace areturnthe method needs (that is stillCS0161).NotNullon a parameter is whatArgumentNullException.ThrowIfNull(argument)uses: after it returns, the argument is known to be non-null.- These are promises, not checks. Prefer an explicit check or
ArgumentNullException.ThrowIfNullwhen callers are not trusted. Use the attributes on code you control and keep their promises true. - They compile into your assembly. Since .NET Core 3.0 the attributes are in the shared framework. In code that targets older frameworks you declare your own copies as
internalclasses with the same names.