'is' versus try cast with null check

后端 未结 7 675
情歌与酒
情歌与酒 2020-12-08 03:28

I noticed that Resharper suggests that I turn this:

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

into this:

var myObjRef = myObj.         


        
7条回答
  •  攒了一身酷
    2020-12-08 04:12

    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)
    {
        ...
    }
    

提交回复
热议问题