Code Inspection: Type check and casts can be merged
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 in not
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
nullis not immediately clear for those who read this code.
ReSharper suggests fixing this code in two different ways.
Use a pattern matching variable
Starting with C# 7.0, we can use the
is operator much more elegantly to combine type testing with initialization of a variable:
Expression is Type variable. Applying this to our example, we'll get the following:
Separate type testing and checking for null
We can also rewrite our code using a safe cast with the as operator and then a null check. This way we'll have one cast instead of two as well as a better separation of concerns: