'is' versus try cast with null check

后端 未结 7 720
情歌与酒
情歌与酒 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:18

    The best option is use pattern matching like that:

    if (value is MyType casted){
        //Code with casted as MyType
        //value is still the same
    }
    //Note: casted can be used outside (after) the 'if' scope, too
    

提交回复
热议问题