Code inspection: Type check and casts can be merged
Category: Potential Code Quality Issues
ID: MergeCastWithTypeCheck
EditorConfig: resharper_merge_cast_with_type_check_highlighting=[error|warning|suggestion|hint|none]
Language: C#, VB.NET
Requires SWA: No
tip
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 ifobj
isnull
is not immediately clear for those who read this code.
void Test(object obj)
{
if (obj is string)
{
string str = (string) obj;
// do something
}
}
ReSharper suggests fixing this code in two different ways.
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:
Suboptimal code
void Test(object obj){ if (obj is string) { string str = (string) obj; // do something }}
After the quick-fix
void Test(object obj){ if (obj is string str) { // do something }}
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:
Suboptimal code
void Test(object obj){ if (obj is string) { string str = (string) obj; // do something }}
After the quick-fix
void Test(object obj){ var str = obj as string; if (str != null) { // do something }}