Rule C#:S3655 false positive for pattern

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.

Hey there!

It seems like this has been raised before.
Since it is the second time, I took a closer look.

I assume that Sonar is missing to look at the implicit operator in OptionalValue which makes the null irrelevant.

You are close enough. Our symbolic execution knows about the implicit operator, but it does not visit it for performance reasons.

The fix seems to be fairly easy (never raise if an implicit operator is used, as it can be anything), so I will implement it on the side and get back to you when we release a new version of SonarLint.

Thanks for the very detailed example, it helped a lot! :slight_smile: