'is' versus try cast with null check

HotN picture HotN · Nov 15, 2012 · Viewed 48.7k times · Source

I noticed that Resharper suggests that I turn this:

if (myObj.myProp is MyType)
{
   ...
}

into this:

var myObjRef = myObj.myProp as MyType;
if (myObjRef != null)
{
   ...
}

Why would it suggest this change? I'm used to Resharper suggesting optimization changes and code reduction changes, but this feels like it wants to take my single statement and turn it into a two-liner.

According to MSDN:

An is expression evaluates to true if both of the following conditions are met:

expression is not null. expression can be cast to type. That is, a cast expression of the form (type)(expression) will complete without throwing an exception.

Am I misreading that, or doesn't is do the exact same checks, just in a single line without the need to explicitly create another local variable for the null check?

Answer

Jeff picture Jeff · Nov 15, 2012

Because there's only one cast. Compare this:

if (myObj.myProp is MyType) // cast #1
{
    var myObjRef = (MyType)myObj.myProp; // needs to be cast a second time
                                         // before using it as a MyType
    ...
}

to this:

var myObjRef = myObj.myProp as MyType; // only one cast
if (myObjRef != null)
{
    // myObjRef is already MyType and doesn't need to be cast again
    ...
}

C# 7.0 supports a more compact syntax using pattern matching:

if (myObj.myProp is MyType myObjRef)
{
    ...
}