9

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)
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
NotADeveloper
  • 347
  • 2
  • 5
  • 17

3 Answers3

9

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.

Community
  • 1
  • 1
Heinzi
  • 167,459
  • 57
  • 363
  • 519
5

Because it was not implemented by Microsoft. But it is e.g. implemented by JetBrains ReSharper.

Visual Studio shows 2 compiler warnings:

Visual Studio

ReSharper shows 4 warnings:

ReSharper

Thomas Weller
  • 55,411
  • 20
  • 125
  • 222
  • While this is great within Visual Studio, it doesn't breaks the build when `treat warnings as errors` is used. See this: http://stackoverflow.com/q/3361495/2557263 – Alejandro Jan 23 '17 at 19:08
-1

The is operator cannot be overloaded.

Note that the is operator only considers reference conversions, boxing conversions, and unboxing conversions. Other conversions, such as user-defined conversions, are not considered.

Source: MSDN

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
kgzdev
  • 2,770
  • 2
  • 18
  • 35