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.