Search code examples
c#asp.net-coreresharpervar

Using 'var' with 'is' causes Resharper to say code is heuristically unreachable


I have this bit of code in a controller

if (ValidateId(id) is BadRequestObjectResult invalid)
    return invalid;

where ValidateId returns a BadRequestObjectResult (a reference type).

If I change the code to

if (ValidateId(id) is var invalid)
    return invalid;

Resharper will complain that all the code after these lines is heuristically unreachable.

I understand that a heuristic is not absolute, but I'm wondering: why Resharper was triggered on this code change?


Solution

  • R# is absolutely right because you use var pattern that always returns true therefore this code is unreachable.

    The var pattern is a catch-all for any type or value. The value of expr is always assigned to a local variable the same type as the compile time type of expr. The result of the is expression is always true. Its syntax is:

    expr is var varname