Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable annotation context vs. nullable warnings context

Microsoft's documentation for nullable reference types explains that the nullable context is a cross-product of two independent binary distinctions: The nullable annotation context can be enabled or disabled, and the nullable warning context can be enabled or disabled. But I am having trouble understanding why one might have one nullable context enabled and the other disabled.

My best explanation is that this tracks a producer-consumer distinction. That is, an enabled annotation context in X allows Y, which uses X, to have meaningful warnings in Y's enabled warning context. Or differently stated, I should enable annotation contexts if I want to improve the warnings for a user of my code (whether that is me in another part of my own code or a separate person using a library that I have created), and I should enable warning contexts if I want to make sure that I am making appropriate checks on code created by others, whether or not that code is properly annotated. Ideally, of course, one probably ought to do both, but one might prioritize one or the other.

Is that the right way to think about it?

like image 681
mbabramo Avatar asked Oct 25 '25 20:10

mbabramo


1 Answers

You have it pretty much right.

Nullable annotations without warnings is mainly for libraries who want to provide useful annotations for their consumers without having to make code changes to remove the warnings in implementations. Several projects in the .NET Core standard library use the <Nullable>annotations</Nullable> setting for this reason. For example: https://github.com/dotnet/runtime/blob/254ef0f7f7f429ec238735fe6132805e3c38a19f/src/libraries/Microsoft.Extensions.Logging.Console/src/Microsoft.Extensions.Logging.Console.csproj#L7

Nullable warnings without annotations is for projects whose maintainers are not interested in annotating their types or changing coding patterns to remove nullable warnings, but they want to get some basic nullability warnings if the compiler observes something is definitely wrong. e.g.

#nullable enable warnings

Widget x = null; // no warning. Type 'Widget' has oblivious nullability here.
if (HasWidget)
{
    x = GetWidget();
}
Console.WriteLine(x.Id); // however, 'x' has a maybe-null state here, so this is a warning

However, the encouraged setting to use is definitely just <Nullable>enable</Nullable> in your project.

like image 59
Rikki Gibson Avatar answered Oct 27 '25 10:10

Rikki Gibson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!