Skip to content
Tutorials Center
My learning

Topics

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.

C#
using System.Diagnostics.CodeAnalysis;

bool TryFind(string key, [NotNullWhen(true)] out string? value);

Try it

C# Teaching the compiler about your contracts

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.

C# AllowNull, DisallowNull, MaybeNull and DoesNotReturn

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

C#
[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

  • NotNullWhen is the workhorse. Every TryXxx method that returns the result in an out parameter should use it ([NotNullWhen(true)] out string? value). The out type stays nullable because it holds null when the method returns false.
  • MaybeNullWhen(false) is its generic twin. When the type is an unconstrained T, you cannot write T? meaningfully for both classes and structs, so bool TryGet(out T value) uses [MaybeNullWhen(false)] out T value. Dictionary<TKey, TValue>.TryGetValue is declared this way.
  • NotNullIfNotNull replaces overloads. Write one method taking and returning string? 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.
  • MemberNotNull pays off in helper methods. If a constructor calls an Init() method that assigns a field, mark Init() so the compiler does not report CS8618 on the constructor.
  • DoesNotReturn ends the flow. After a call to such a method the compiler treats the code as unreachable for null analysis, so a check like if (x is null) Fail(); leaves x non-null afterwards. It does not replace a return the method needs (that is still CS0161).
  • NotNull on a parameter is what ArgumentNullException.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.ThrowIfNull when 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 internal classes with the same names.