Reputation: 43
Resharper is showing a warning "The source expression always matches the provided pattern" and underlining the case int
of the last case statement.
The roslyn fix is "to object pattern" and changes it to case { } upperLvl when upperlevel >= 20
Can anybody enlighten me as to why this warning is shown and if I should apply that change?
public static decimal CalculateCouponValue(int level)
{
switch (level)
{
default:
return 20;
case 8:
case 9:
case 10:
return 25;
case 11:
case 12:
case 13:
return 30;
case 14:
case 15:
case 16:
return 35;
case 17:
case 18:
case 19:
return 40;
case int upperLvl when upperLvl >= 20: //The source expression always matches the provided pattern
return 50;
}
}
Upvotes: 1
Views: 466
Reputation: 431
ReSharper issues this warning because expression of type int
indeed always matches type pattern int upperLvl
, in other words specifying the same type is redundant. The proposed transformation of type pattern into object pattern ({}
) gives equivalent semantics (you may check it here) but personally I prefer var pattern in such cases:
case var upperLvl when upperLvl >= 20:
return 50;
which also preseves the original semantics. The var pattern always succeeds but kind of indicates that you just want to introduce new variable here.
Note that all these options are equivalent here because you're switching on expression of value type but there are subtle differences when it comes to reference types.
Let's say you're switching on some string
value:
public static decimal GetDiscountByCode(string code)
{
switch (code.ToUpper())
{
case "XMAS2020":
return 25;
case "NEWYEAR2020":
return 20;
case string specialCode
when TryExtractDiscount(specialCode, out var discount):
return discount;
default:
return 0;
}
}
Here type pattern string specialCode
performs the null check meaning that null
value doesn't match this pattern.
Replacing the type pattern with object pattern {} specialCode
is equivalent because object pattern also performs null check.
But using the var pattern instead would change the semantics because as I mentioned earlier it always succeeds without performing any additional checks.
You can quickly check how C# lowers all these high-level constructs at wonderful website https://sharplab.io/.
And finally. The decision on whether to apply the fix proposed by ReSharper is always up to you! If you really prefer the type pattern syntax you may change severity of this particular inspection from Warning
to Hint
or even disable it completely: just press Alt+Enter
on highlighted code, expand the menu item Inspection: "The source expression is always of pattern's type" | Configure inspection severity and select another severity which works best for you :)
Upvotes: 3