Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between NullableContextOptions and NullableReferenceTypes?

I've been playing with new c# 8.0 NullableReferenceTypes feature for a while. And I'm little bit confused about turning this feature on via changing .csproj file.

I mean in order to enable this feature you have to put the following lines in your .csproj file:

<PropertyGroup>
  <LangVersion>8.0</LangVersion>
  <NullableContextOptions>enable</NullableContextOptions>
</PropertyGroup>

But also I've found another one way:

<PropertyGroup>
  <LangVersion>8.0</LangVersion>
  <NullableReferenceTypes>true</NullableReferenceTypes>
</PropertyGroup>

So it almost the same but anyway. What is the difference between NullableContextOptions and NullableReferenceTypes?

like image 288
isxaker Avatar asked Feb 24 '19 14:02

isxaker


People also ask

What is #nullable disable?

Generators can opt-in using the #nullable preprocessor directive. By default, nullable annotation and warning contexts are disabled. That means that your existing code compiles without changes and without generating any new warnings.

What are nullable reference types?

Nullable reference types aren't new class types, but rather annotations on existing reference types. The compiler uses those annotations to help you find potential null reference errors in your code. There's no runtime difference between a non-nullable reference type and a nullable reference type.

Should I use nullable reference types?

Although using nullable reference types can introduce its own set of problems, I still think it's beneficial because it helps you find potential bugs and allows you to better express your intent in the code. For new projects, I would recommend you enable the feature and do your best to write code without warnings.

What is the point of nullable string?

Nullable type in C# is used to assign null values to value type variables like to the variables of type int, float, bool, etc., because they cannot store null values. On the other hand, we cannot use nullable with string or any other reference type variable because it can directly store null value.


2 Answers

In earlier previews, the compiler only allowed two settings (true/false, meaning on/off).

In later previews (starting with preview 2), the compiler allowed more options, so the name of the setting and the possible options were changed.

Here's the documentation of the possible options and their meanings: https://docs.microsoft.com/en-us/dotnet/csharp/nullable-references

like image 154
Julien Couvreur Avatar answered Oct 17 '22 07:10

Julien Couvreur


As of .NET Conf 2019 (C# 8.0 release), the correct way to achieve default non-nullable reference types is:

<PropertyGroup>
    <LangVersion>8.0</LangVersion>
    <Nullable>enable</Nullable>
</PropertyGroup>
like image 27
Lyra Avatar answered Oct 17 '22 06:10

Lyra