Checking if an object is null in C#

前端 未结 18 1765
情深已故
情深已故 2020-11-28 02:12

I would like to prevent further processing on an object if it is null.

In the following code I check if the object is null by either:

if (!data.Equal         


        
18条回答
  •  有刺的猬
    2020-11-28 02:41

    As others have already pointed out, it's not data but rather likely dataList that is null. In addition to that...

    catch-throw is an antipattern that almost always makes me want to throw up every time that I see it. Imagine that something goes wrong deep in something that doOtherStuff() calls. All you get back is an Exception object, thrown at the throw in AddData(). No stack trace, no call information, no state, nothing at all to indicate the real source of the problem, unless you go in and switch your debugger to break on exception thrown rather than exception unhandled. If you are catching an exception and just re-throwing it in any way, particularly if the code in the try block is in any way nontrivial, do yourself (and your colleagues, present and future) a favor and throw out the entire try-catch block. Granted, throw; is better than the alternatives, but you are still giving yourself (or whoever else is trying to fix a bug in the code) completely unnecessary headaches. This is not to say that try-catch-throw is necessarily evil per se, as long as you do something relevant with the exception object that was thrown inside the catch block.

    Then there's the potential problems of catching Exception in the first place, but that's another matter, particularly since in this particular case you throw an exception.

    Another thing that strikes me as more than a little dangerous is that data could potentially change value during the execution of the function, since you are passing by reference. So the null check might pass but before the code gets to doing anything with the value, it's changed - perhaps to null. I'm not positive if this is a concern or not (it might not be), but it seems worth watching out for.

提交回复
热议问题