Null parameter checking in C#

前端 未结 9 687
失恋的感觉
失恋的感觉 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 21:51

    Without an explicit if check, it can be very difficult to figure out what was null if you don't own the code.

    If you get a NullReferenceException from deep inside a library without source code, you're likely to have a lot of trouble figuring out what you did wrong.

    These if checks will not make your code noticeably slower.


    Note that the parameter to the ArgumentNullException constructor is a parameter name, not a message.
    Your code should be

    if (s == null) throw new ArgumentNullException("s");
    

    I wrote a code snippet to make this easier:

    
    
        
            
    Check for null arguments tna Code snippet for throw new ArgumentNullException SLaks Expansion SurroundsWith
    Parameter Paremeter to check for null value

提交回复
热议问题