S2259 `null` on at least one execution path despite `case null:`

enum MyEnum
{
    One,
    Two,
    Three,
    Four,
    Five
}

void Foo()
{
    var myObject = GetObjectFromOutside();

    switch (myObject?.EnumValue)
    {
        case MyEnum.One:
            throw new MyException("Invalid value.");
        case MyEnum.Two:
        case null:
            throw new MyException("Invalid or null value.");
        case MyEnum.Three:
            break;
        default:
            throw new ArgumentOutOfRangeException(
                nameof(myObject.EnumValue),
                $"Unexpected value ${myObject.EnumValue}");
    }
}

This raises S2259 - "myObject is null on at least one execution path" in the default case (for the myObject.EnumValue dereferencing). But if myObject was null, then myObject?.EnumValue would also be null and the switch would hit the null case, throwing an exception. So default is unreachable if myObject is null.

Scanned using SonarScanner for MSBuild 4.6.1, .NET Core version, onto SonarCloud. .NET Core 2.2, C# 7.3.

1 Like

hey @V0ldek and welcome to our community!

thanks for the detailed reproducer, I’ve added your example to #2338 which tracks this problem

1 Like