Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The given expression is always of the provided type

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)
like image 269
NotADeveloper Avatar asked Jan 23 '17 13:01

NotADeveloper


1 Answers

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.

like image 50
Heinzi Avatar answered Sep 20 '22 23:09

Heinzi