ReSharper
 
Get ReSharper
You are viewing the documentation for an earlier version of ReSharper.

Code Inspection: Type check and casts can be merged

Last modified: 21 July 2022

The type-testing is operator in its classical form (Expression is Type) returns true only when the runtime type of Expression is compatible with Type and the result of Expression is not null.

When we use is to check the compatibility before casting, like in the below example, we have at least two problems:

  • We make the type check twice for no reason, which can affect performance if we do it inside a loop.

  • The fact that the program execution will not get into the if statement if obj is null is not immediately clear for those who read this code.

ReSharper suggests fixing this code in two different ways.