Why does Visual Studio warn about this when using is
on value types, but doesn't when on reference types? Lines 1 and 2 raise the warning, while lines 3 and 4 don't.
if (5 is object)
if (new Point() is object)
if ("12345" is object)
if (new StringBuilder() is object)
It's a heuristic and heuristics are, by definition, incomplete.
The source code for this heuristic can be found here: Roslyn Source: Binder.GetIsOperatorConstantResult. The code contains the following quote:
// The result of "x is T" can be statically determined to be true if x is an expression
// of non-nullable value type T. If x is of reference or nullable value type then
// we cannot know, because again, the expression value could be null or it could be good.
Obviously, the heuristic could be improved if it is known (as in your examples) that x
is a non-null expression. However, as Eric Lippert writes in his blog, every warning (in fact - every compiler feature) has a cost, and, apparently, the Roslyn developers did not consider this feature important enough for this release.
As Thomas Weller's answer shows, there are third-party solutions filling this gap.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With