JetBrains Rider 2024.3 Help

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 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.

void Test(object obj) { if (obj is string) { string str = (string) obj; // do something } }

JetBrains Rider 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:

void Test(object obj) { if (obj is string) { string str = (string) obj; // do something } }
void Test(object obj) { if (obj is string str) { // do something } }

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:

void Test(object obj) { if (obj is string) { string str = (string) obj; // do something } }
void Test(object obj) { var str = obj as string; if (str != null) { // do something } }
Last modified: 08 April 2024