Language: C# 8 on .NET 8.0
Rule: S3655 (reference is null on at least one execution path)
Scanners:
- SonarLint for Visual Studio 2022 version 8.5.0.10497.
This code gives warning:
private readonly struct OptionalValue<T> where T : struct
{
public readonly T _value;
public readonly bool _isSpecified;
public OptionalValue(T value)
{
_value = value;
_isSpecified = true;
}
public static implicit operator OptionalValue<T>(T? value) => value.HasValue ? new(value.Value) : default;
}
public struct MyStruct
{
public int Value { get; set; }
};
public struct MyOtherStruct
{
public MyStruct? Inner { get; set; }
};
MyOtherStruct t = new MyOtherStruct();
OptionalValue<int> myObject = t.Inner?.Value ?? null;
This results in the following message on t.Inner?.Value ?? null;
(last line):
S3655: ‘ t.Inner?.Value ?? null’ is null on at least one execution path.
I assume that Sonar is missing to look at the implicit operator in OptionalValue which makes the null irrelevant.