CS8632 - The annotation for nullable reference types should only be used in code within a ‘#nullable’ annotations context.
I copy/pasted the following code from an example I found on the web to test source generators(but that is not where this post is about today).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public sealed class Source { | |
public decimal Amount { get; set; } | |
public Guid Id { get; set; } | |
public int Value { get; set; } | |
public string? Name { get; set; } | |
} |
Building this code resulted in the following warning:
Do you have any idea why?
Take a look at the ‘Name’ property. Notice the usage of ‘?’. This is part of the introduction of nullable reference types and declares the string as nullable.
Nullable reference types are available beginning with C# 8.0, in code that has opted in to a nullable aware context. This is what the warning message is referring to. We need to enable nullable reference type support in our project.
This can be done by adding <Nullable>enable></Nullable> in our csproj file:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<PropertyGroup> | |
<OutputType>Exe</OutputType> | |
<TargetFramework>net5.0</TargetFramework> | |
<Nullable>enable</Nullable> | |
</PropertyGroup> |