Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enabling nullable types makes no difference

I had some issues with enabling non-nullable reference types. Not sure if it's an actual issue or if it's me that isn't keeping up with the latest naming / setup of this.

This is my current setup (using VS Code):

Dotnet version: 3.0.100-preview6-012264
Omnisharp: 1.20.0

I noticed that the flag for enabling nullable has changed multiple times but as I could see in documentation, and on the internet, latest seemed to be <Nullable/> which I enabled in all (both main web project shown below and in my .NET Standard 2.0 class libs):

<Project Sdk="Microsoft.NET.Sdk.Web">

  ...

  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <LangVersion>8.0</LangVersion>
    <Nullable>enable</Nullable>
    <WarningsAsErrors>CS8600;CS8602;CS8603</WarningsAsErrors>
  </PropertyGroup>

</Project>

If I use #nullable enable in the file I'm testing, I see that the IntelliSense switches directly to, what seems to be, the right alerts. Adding this in the file will also make the build fail (which is the behavior I'm seeking).

What am I missing here to get this working on the project level?

like image 971
Base Avatar asked Jun 28 '19 17:06

Base


People also ask

What does nullable enable do?

Nullable reference types enable you to declare if variables of a reference type should or shouldn't be assigned a null value. The compiler's static analysis and warnings when your code might dereference null are the most important benefit of this feature.

What is the point of having 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.

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.

What is nullable enable in Csproj?

The nullable annotation context and nullable warning context can be set for a project using the <Nullable> element in your . csproj file. This element configures how the compiler interprets the nullability of types and what warnings are emitted.


1 Answers

To summarize the discussion above:

The naming of this currently differs between omnisharp (vs code) and when using Visual Studio it seems. So the MS documentation, which specifies <Nullable> is not applicable. For omnisharp / vs code <NullableContextOptions>enable</NullableContextOptions> needs to be used instead (until omnisharp has been updated).

like image 99
Base Avatar answered Oct 03 '22 11:10

Base