Why does Resharper think my class members are "non nullable"?
In my .C#/.NET Core 3.1 App, Resharper complains about the fact that my class is failing to initialize one of its properties because, it says, "Non-nullable class properties are not initialized on all paths". Then it names the properties. They are all public properties with public getters and private setters that are definitely nullable. They are designed to be nullable, depending on which constructor the user uses. Sometimes they can be initialized later one.
I have not marked these properties it with any attributes to indicate otherwise
So can anyone tell me why is CA might think this thing is non-nullable?
Here is the code to illustrate. Note the properites "FlatField" and "Model". The first constructor complains that I failed to initialize both of them. The second complains that I failed to initialize "Model"
public class CalibrationJob : JobVm
{
private readonly ICaptureService _capture;
private List<ITargetContextJob> ScanJobs { get; }
private List<IParameter> Parameters { get; }
private readonly string _calibrationName;
private readonly string _fileNameBase;
public ICalibrationModel Model { get; private set; }
public IDevice Device { get; } // Camera used to capture the scans.
public CalibrationJob(
IDevice device,
ILogger logger,
ICaptureService capture,
IEnumerable<ITargetContextJob> scanJobs)
: base(logger, Strings.Calibrate)
{
_capture = capture;
Device = device ?? throw new ArgumentException(Strings.NoDevice);
ScanJobs = scanJobs.ToList();
}
public CalibrationJob(
IDevice device,
ILogger logger,
ICaptureService capture,
IEnumerable<ITargetContextJob> scanJobs,
IEnumerable<IParameter> parameters,
FlatField flatField)
: base(logger, Strings.Tune)
{
_capture = capture;
FlatField = flatField;
Device = device ?? throw new ArgumentException(Strings.NoDevice);
ScanJobs = scanJobs.ToList();
Parameters = parameters?.ToList() ?? throw new ArgumentNullException(nameof(parameters));
}
Please sign in to leave a comment.
Does your project have the "nullable reference types" feature enabled?
Design with nullable reference types | Microsoft Docs
If so, you'll need to explicitly mark all reference type fields, parameters, and variables which are expected to contain null as nullable.
Wow. That opened a can of worms.
The answer to your question is yes, apparently this one particular project - which is C# 8.0 -- has the following tag in its .csproj file
I don't know how it go in there. I don't remember putting it there. But regardless this is clearly why it's happening. And your answer forced me to dig into understanding nullable reference types, what they are and what they do.
Aow I've drunk the Cool-Aid. I'm going to be enabling this in all my projects and setting it to generate warnings -- which will prevent me from building until i address all such issues. Which I like
So I understand now, thank you.