Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The annotation for nullable reference types should only be used in code within a '#nullable' context. #9517

Closed
arivoir opened this issue Dec 10, 2018 — with docs.microsoft.com · 47 comments
Assignees
Milestone

Comments

Copy link

arivoir commented Dec 10, 2018

After converting my project to c#8 and fixing all the problems. Every warning was removed, and suddently I got 97 Warnings of these
Warning CS8632 The annotation for nullable reference types should only be used in code within a '#nullable' context.

Do I need to add the #nullabel context if I used <NullableReferenceTypes>true</NullableReferenceTypes> in the proj file?


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

@BillWagner BillWagner added needs-more-info Needs more info from OP. Auto-closed after 2 weeks if no response. [org][resolution] and removed ⌚ Not Triaged Not triaged labels Dec 10, 2018
@BillWagner
Copy link
Member

@arivoir Adding the <NullableReferenceTypes>true</NullableReferenceTypes> in your csproj, in a PropertyGroup should work fine. A couple things to check:

  • Do you also have the C# 8 compiler turned on? Check the LangVersion element to make sure its set to 8.0
  • Did those warnings go away as the IDE re-ran the analysis on the code? I've found initial incorrect warning indicators go away after the IDE has run a full analysis on the project.

@arivoir
Copy link
Author

arivoir commented Dec 11, 2018

@BillWagner Yes, I have the LangVersion tag correctly. Actually I could migrate the project correctly and fix all the bugs that appeared because of the change to c#8. Now I'm seeing the warnings are comming from the Intellisense, because when I change the "Build+IntelliSense" combo box of the "Error List" to just "Build" they go away. Neither Analyze nor Clean nor Rebuild nor deleting bin and obj folders make any difference.

I'm using the following project to test Open.Flickr

Please let me know if you need more info.

@BillWagner
Copy link
Member

Thanks @arivoir

adding @jcouv and @Pilchie who can help route this to the right repo.

@jcouv
Copy link
Member

jcouv commented Dec 11, 2018

@arivoir It sounds like a bug with the "Error List" being out of date and not refreshing properly. I assume that closing and re-opening VS solves the problem.

Could you file an issue in https://github.com/dotnet/roslyn if you are able to reproduce the issue? Thanks

@arivoir
Copy link
Author

arivoir commented Dec 11, 2018

@jcouv I tried restarting Visual Studio and even the PC, but the problem is still there. Once you open the project it takes some seconds, apparently running the Intelli-sense, and the "Error List" is re-populated with these warnings.

@jcouv
Copy link
Member

jcouv commented Dec 11, 2018

@arivoir One more question: if you build the project (F6) and look at the Output pane, do these warnings also appear there?

@arivoir
Copy link
Author

arivoir commented Dec 11, 2018

@jcouv No, they do not appear in the "Output" pane. Only in "Error List"

@jcouv
Copy link
Member

jcouv commented Dec 11, 2018

@arivoir I talked to a coworker and I think we've figured this out.
There are two types of project files: legacy-style (big and gnarly) and new-style (short and sweet). The NullableRerenceTypes property is only fully understood in the new-style project files in dev16.0 preview1.

I suspect you have a legacy-style project file. So what happens is that Build does the right thing, but when the IDE tries to approximate the build process (Intellisense) it did not properly account for the NullableReferenceTypes property.

This will be fixed by the time C# 8.0 ships, and it is tracked by dotnet/project-system#4058

In the meantime, you can use the "Build" filter (instead of "Build+Intellisense"), or if the project is small you could add #nullable enable to every file. Sorry for the confusion and inconvenience.

@arivoir
Copy link
Author

arivoir commented Dec 11, 2018

@jcouv I'm afraid it is not the case. It's actually using the new style Open.Flickr.csproj You can get the project and try in your environment. Please let me know whether you're having the same issue as me.

@jcouv
Copy link
Member

jcouv commented Dec 11, 2018

@arivoir This is mysterious. I cloned your project and opened it with a dev16 preview, but couldn't repro.
My preview is an internal preview of 2.0 though, so I will try again tonight on a machine with preview1.

image
Tested on VisualStudio.16.IntPreview/16.0.0-pre.2.0+28410.104.d16.0stg

@arivoir
Copy link
Author

arivoir commented Dec 11, 2018

I originally found this problem in preview1, and then upgraded to preview1.1 where the problem continued.

Please let me know if there is any log or something I can make to help.

@jcouv
Copy link
Member

jcouv commented Dec 12, 2018

I tried this on a preview 1 (VisualStudio.16.Preview/16.0.0-pre.1.0+28329.73), but still couldn't repro.

I would be tempted trying to "repair" your preview 1 (or 1.1) installation.

Tagging @heejaechang in case he has some ideas. To summarize, the issue is that the "Error List" with "Build+IntelliSense" filter shows some nullable warnings that appear nowhere else (neither in "Output" pane, nor in "Build" filter).
Do you know how to troubleshoot this?

@jcouv
Copy link
Member

jcouv commented Dec 13, 2018

Opened a roslyn issue: dotnet/roslyn#31765

Feel free to close this issue (there is no problem with docs).

@BillWagner
Copy link
Member

Closing this based on above discussion and issue.

@xuhongxu96
Copy link

Hi, I have the same issue. And this warning will show in Build Only Error List as well as the Output window.

image

Visual Studio 2019 Preview 2

@jcouv
Copy link
Member

jcouv commented Jan 24, 2019

@xuhongxu96 In preview2, the name of the build property changed.
Use <NullableContextOptions>enable</NullableContextOptions> instead. You may have to close/re-open VS for it to take effect.

Details https://github.com/dotnet/roslyn/blob/master/docs/features/nullable-reference-types.md#setting-project-level-nullable-context

@BillWagner
Copy link
Member

I'm reopening this.

I'll update the docs in the next two weeks to reflect the change in the build property.

@BillWagner BillWagner reopened this Jan 24, 2019
@BillWagner BillWagner added P1 and removed needs-more-info Needs more info from OP. Auto-closed after 2 weeks if no response. [org][resolution] product-question labels Jan 24, 2019
@isxaker
Copy link

isxaker commented Mar 4, 2019

@isxaker Is your .NET Framework project using the or the old style CSPROJ file? I don't know if that makes a difference, but it's worth knowing.

@BillWagner

Didn't get it clear enough.
I just go to VS2019 click new project -> console app(.net framework)
And that's all. I can't turn this feature on via .csproj file.
The only one way how I'm able to turn this feature on for .net framework app is using #nullable enable

@bugproof
Copy link

bugproof commented Mar 15, 2019

@isxaker works fine for me with .NET Framework. Maybe it's fixed now?

@isxaker
Copy link

isxaker commented Mar 15, 2019

@isxaker works fine for me with .NET Framework. Maybe it's fixed now?

can you post here your .csproj file please

@bugproof
Copy link

bugproof commented Mar 15, 2019

@isxaker

Okay, I've tested it and it doesn't seem with to work with .NET Framework old csproj format unless you add #nullable enable in your code.

<NullableContextOptions>enable</NullableContextOptions> is ignored in old style projects.

but after converting to new csproj format (https://github.com/hvanbakel/CsprojToVs2017) it works with .NET Framework:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <ProjectGuid>{C192613D-2431-40F2-BA13-33B5B55241A5}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <TargetFramework>net45</TargetFramework>
    <LangVersion>8.0</LangVersion>
    <NullableContextOptions>enable</NullableContextOptions>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <AssemblyTitle>NullableReferenceTypesNetFramework</AssemblyTitle>
    <Product>NullableReferenceTypesNetFramework</Product>
    <Copyright>Copyright ©  2019</Copyright>
    <OutputPath>bin\$(Configuration)\</OutputPath>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugType>full</DebugType>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
  </PropertyGroup>
  <PropertyGroup>
    <StartupObject />
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="System.Data.DataSetExtensions" />
    <Reference Include="Microsoft.CSharp" />
    <Reference Include="System.Net.Http" />
  </ItemGroup>
</Project>

Also, if you're using ReSharper or Rider you have to install EAP.

additional notes:

Nullable<string> doesn't compile, and string? is missing System.Nullable properties like HasValue and Value

@jcouv described that earlier in this discussion

@egil
Copy link
Contributor

egil commented May 22, 2019

This issue seem to be back with with the latests Visual Studio 2019 Preview (16.2.0 Preview 1.0). After upgrading, I get multiple "CS8632 C# The annotation for nullable reference types should only be used in code within a context." when I open my solution https://github.com/egil/bootstrap-dotnet.

Adding #nullable enable to affected files solves the problem, so it seems like <NullableContextOptions>enable</NullableContextOptions> is not being picked-up correctly.

One of the projects in the solution that fails to compile with that warning is tests/Egil.RazorComponents.Bootstrap.Tests that has this .csproj:

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

  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <LangVersion>8.0</LangVersion>
    <NullableContextOptions>enable</NullableContextOptions>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <IsPackable>false</IsPackable>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
    <CodeAnalysisRuleSet>Egil.RazorComponents.Bootstrap.Tests.ruleset</CodeAnalysisRuleSet>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <CodeAnalysisRuleSet>Egil.RazorComponents.Bootstrap.Tests.ruleset</CodeAnalysisRuleSet>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.1.0" />
    <PackageReference Include="Shouldly" Version="3.0.2" />
    <PackageReference Include="xunit" Version="2.4.1" />
    <PackageReference Include="xunit.runner.visualstudio" Version="2.4.1">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\..\src\Egil.RazorComponents.Bootstrap\Egil.RazorComponents.Bootstrap.csproj" />
  </ItemGroup>

</Project>

I have tried reinstalling dotnet-sdk-3.0.100-preview5-011568-win-x64.exe and repairing Visual Studio.

@AlexanderTaeschner
Copy link

The option has been renamed to <Nullable>, so that <Nullable>enable</Nullable> in the csproj file now enables the nullability feature for all code files in the project (see dotnet/roslyn#35432).

@egil
Copy link
Contributor

egil commented May 22, 2019

The option has been renamed to <Nullable>, so that <Nullable>enable</Nullable> in the csproj file now enables the nullability feature for all code files in the project (see dotnet/roslyn#35432).

Great. That is a good simplification. I must have missed that in the release notes. Thanks for the hint.

@flcdrg
Copy link
Contributor

flcdrg commented May 23, 2019

Just to clarify, SDK 2.2.204, 2.2.300 and 3.0.100-preview5-011568 still appear to use NullableContextOptions in Microsoft.CSharp.Core.targets

The same with Visual Studio 2019 16.1 (C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\Roslyn\Microsoft.CSharp.Core.targets)

2019 16.2 Preview does have have it though (C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\MSBuild\Current\Bin\Roslyn\Microsoft.CSharp.Core.targets)

@dominikjeske
Copy link

I just enabled nullable like this

<PropertyGroup>
    <TargetFramework>netstandard2.1</TargetFramework>
    <LangVersion>8.0</LangVersion>
    <Nullable>enable</Nullable>
  </PropertyGroup>

and my project is failing to compile 'Invalid 'nullable' value: 'Enable' for C# 7.3. Please use language version 'preview' or greater'. I'm using .NET Core 3 preview 6 and Visual Studio 16.2 Preview 2

@bdbc78
Copy link

bdbc78 commented Dec 17, 2019

I'm getting this issue. Here's my project settings:
<PropertyGroup> <TargetFramework>netcoreapp3.0</TargetFramework> <nullable>enable</nullable> <AssemblyName>[assemblyname]</AssemblyName> </PropertyGroup>

Adding LangVersion doesn't have any impact. This appears to align with updating to VS2019 16.4, however I cannot say that for certain. Nullable reference types were being used prior to the update without this message being decorated everywhere.

@Tiramonium
Copy link

Tiramonium commented Dec 17, 2019

I was facing this kind of issue at my nullable reference type property declarations, so I kind of accidentally found the solution for this warning by setting nullable as you do a region block and the parameter values dug up by @xuhongxu96 and @jcouv.

So in the end my code ended up looking like this

#nullable enable
    public Type? TypeProp { get; set; }
#nullable disable

So my guess is that depending on the type of situation you are facing, you should use one of the values mentioned in @jcouv 's answer, then disabling the setting by ending the block with #nullable disable, if you prefer.

Also, none of that .csproj tinkering was necessary in the end.

@bdbc78
Copy link

bdbc78 commented Dec 17, 2019

Except that's not a solution to the issue, since setting <nullable>enabled</nullable> in the project file is supposed to negate the need for that directive. In fact, when nullable is enabled, really the only practical usage of the directives at that point is to use them to phase in the nullable functionality file by file (by using #nullable disable).

For some reason, in my situation the evaluation is ignoring the existence of the nullable setting in the project file.

@Tiramonium
Copy link

Tiramonium commented Dec 17, 2019

My latest solution was to implement it as suggested by other answers and it worked just fine. NET Core versions older than 3.0 may still face the issue probably because their framework versions don't use C# 8.0 yet, which is used by default by VS 2019 as its IntelliSense compiler, as far as I know. Those cases will require either different fixes, maybe tinkering with the IDE settings, or for them to be worked on exclusively via VS 2017 instead.

Based on Microsoft's own documentation, I reached the following solution:

<Project Sdk="Microsoft.NET.Sdk.Web">
    <PropertyGroup>
        <TargetFramework>netcoreapp3.1</TargetFramework>
        <LangVersion>8.0</LangVersion>
        <Nullable>annotations</Nullable>
    </PropertyGroup>
</Project>

That enables the nullable context, eliminating the CS8632 warning message - disregarding the need for a #nullable block declaration - and disabled the nullable warning context, ensuring that nullable checks will be enforced against nullable reference types.

Also, you won't see it happen until you restart VS completely, since IntelliSense uses the last loaded setting for real time compilation.

@bdbc78
Copy link

bdbc78 commented Dec 18, 2019

All of my project settings are correct as it pertains to what behavior I am expecting to see in the project regarding any nullable reference type warnings. However, after further investigation on another developer's development environment, it was determined that the latest version of ReSharper is the cause of the issues I'm seeing. So I will redirect my issue reporting to their issue tracker. Thank you.

@KishorTiwari
Copy link

Thanks @Tiramonium It worked for me.

@ata18
Copy link

ata18 commented May 13, 2021

I have the following in my.csproj file. When running in vscode on my local machine, it doesn't throw any warnings/errors. But when I build it in the Azure pipelines task, I get a bunch of these CS8632 warnings.. Any idea what might be happening?

 <TargetFramework>net5.0</TargetFramework>
 .
 .
 <LangVersion>9.0</LangVersion>
<Nullable>enable</Nullable>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AnalysisMode>AllEnabledByDefault</AnalysisMode>
<EnableNETAnalyzers>true</EnableNETAnalyzers>

@dotnet-bot dotnet-bot added the ⌚ Not Triaged Not triaged label May 13, 2021
@jcouv
Copy link
Member

jcouv commented May 17, 2021

@ata18 Just to confirm, when you're doing a local build (say from command-line, not VSCode), are you getting the expected nullability warnings?

There's also a small possibility that the specific compiler versions used in pipeline task and locally differ. The nullability feature has had revisions. You could troubleshoot this by confirming the compiler versions (add #error version to your source to create a diagnostic outputting the details).

@Tiramonium
Copy link

@ata18 first of all, if you noticed, this warning got introduced in C# 8.0 and I'm assuming it carried onto 9.0 as well, which is used by NET 5.0. If you had read this thread you would have noticed that <Nullable>true</Nullable> enables this check instead of disabling it.

Another thing I noticed in your settings that might be causing unexpected results is that you set it to treat warnings as errors with <TreatWarningsAsErrors>true</TreatWarningsAsErrors>, so your Azure Pipeline(s) might be failing precisely because of that.

@ata18
Copy link

ata18 commented May 24, 2021

@jcouv Thanks for your response, I will check the compiler versions.

@Tiramonium You are correct. I know that true enables the check. And I have fixed all the errors related to nullable references and running it locally has no more warnings. However, I still get these CS8632 warnings in Azure pipelines.

##[warning]Api\Models\V1\ApiResponse.cs(12,22): Warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.

Line 12: public string? Message { get; }

What is wrong here?

@Tiramonium
Copy link

Tiramonium commented Jun 29, 2021

@ata18 I just noticed a very basic error in your code. String is a C# reference type which inherently implements its nullable version, same with generic reference types like object and dynamic, therefore there's no such thing as a string? property.

@ata18
Copy link

ata18 commented Jun 29, 2021

@FreakyAli
Copy link

Enabling <Nullable>enable</Nullable> on my current project just got it from 1 warning to 265 warnings 😱

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Archived in project
Development

No branches or pull requests