'is' versus try cast with null check

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

    To me this seems dependent on what the odds are that it's going to be of that type or not. It would certainly be more efficient to do the cast up front if the object is of that type most of the time. If it's only occasionally of that type then it may be more optimal to check first with is.

    The cost of creating a local variable is very negligible compared to the cost of the type check.

    Readability and scope are the more important factors for me typically. I would disagree with ReSharper, and use the "is" operator for that reason alone; optimize later if this is a true bottleneck.

    (I'm assuming that you are only using myObj.myProp is MyType once in this function)

提交回复
热议问题