ReSharper
 
Get ReSharper
Get your hands on the new features ahead of the release by joining the Early Access Program for ReSharper 2025.1! Learn more

Code inspection: Type check and casts can be merged

Last modified: 08 April 2024

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.