What does the "Nullable context" actually do?

Viewed 392

I've seen the documentation for C#'s nullable contexts but there is something I don't understand:

Does enabling the nullable context for any piece of code JUST makes it start showing warnings when null may be assigned to a "shouldn't be null" type?

I was under the impression it would tell the compiler "I promise this won't be null, so shut up about it." but it seems it does the opposite? "Let me know when something can be null, because I'm paranoid."?

Is that it?

1 Answers

Microsoft introduced in C# 8 "nullable aware context".

In a nullable aware context:

  • A variable of a reference type T must be initialized with non-null, and may never be assigned a value that may be null.
  • A variable of a reference type T? may be initialized with null or assigned null, but is required to be checked against null before de-referencing.
  • A variable m of type T? is considered to be non-null when you apply the null-forgiving operator, as in m!.

The distinctions between a non-nullable reference type T and a nullable reference type T? are enforced by the compiler's interpretation of the preceding rules. A variable of type T and a variable of type T? are represented by the same .NET type.

Nullable reference types

Examples:

string notNull = "Hello";
string? nullable = default;
notNull = nullable!; // null forgiveness

This feature can be turned on and off using the <nullable>enable</nullable or disable attribute in the Project file. Since the feature is disable by default, the attribute can also be removed to disable it.

Nullable contexts

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
  </PropertyGroup>

Additional information:

Learn techniques to resolve nullable warnings

Update a codebase with nullable reference types to improve null diagnostic warnings

Related