I am getting this warning for most properties specially for string. Sample Attachment.
After carefully observing this error message, it makes sense for those properties. In order to minimize the likelihood that our code causes the runtime to throw System.NullReferenceException, we need to resolve this warning.
Therefore, the complier is giving the warning in the solution that the default assignment of your properties (which is null) doesn’t match its state type (which is non-null string).
https://docs.microsoft.com/en-us/dotnet/csharp/nullable-references
We can resolve this error in 3 ways.
Solution 1
We can simply make the properties nullable, as shown below:
Sample:
public class AppSetting { public string? ReferenceKey { get; set; } public string? Value { get; set; } public string? Description { get; set; } }
Solution 2
We can assign default value to those properties as shown below:
public class AppSetting { public string ReferenceKey { get; set; } = “Default Key”; public string? Value { get; set; } = “Default Value”; public string? Description { get; set; } = “Default Description”; }
Alternatively, you can give a reasonable default value for non-nullable strings as string.empty.
Solution 3
You can disable this warning from project level. You can disable by removing the below line from project file csproj or setting.
<Nullable>enable</Nullable>
https://docs.microsoft.com/en-us/dotnet/csharp/nullable-references#nullable-contexts
These are three ways you can overcome the above warning.