Null parameter checking in C#

前端 未结 9 539
失恋的感觉
失恋的感觉 2021-01-29 21:46

In C#, are there any good reasons (other than a better error message) for adding parameter null checks to every function where null is not a valid value? Obviously, the code tha

相关标签:
9条回答
  • 2021-01-29 22:08

    You might want to take a look at Code Contracts if you need a nicer way to make sure you do not get any null objects as a parameter.

    0 讨论(0)
  • 2021-01-29 22:12

    It saves some debugging, when you hit that exception.

    The ArgumentNullException states explicitly that it was "s" that was null.

    If you don't have that check and let the code blow up, you get a NullReferenceException from some unidentified line in that method. In a release build you don't get line numbers!

    0 讨论(0)
  • 2021-01-29 22:13

    I've been using this for a year now:

    _ = s ?? throw new ArgumentNullException(nameof(s));
    

    It's a oneliner, and the discard (_) means there's no unnecessary allocation.

    0 讨论(0)
提交回复
热议问题