Null parameter checking in C#

前端 未结 9 542
失恋的感觉
失恋的感觉 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:55

    Original code:

    void f(SomeType s)
    {
      if (s == null)
      {
        throw new ArgumentNullException("s cannot be null.");
      }
    
      // Use s
    }
    

    Rewrite it as:

    void f(SomeType s)
    {
      if (s == null) throw new ArgumentNullException(nameof(s));
    }
    

    The reason to rewrite using nameof is that it allows for easier refactoring. If the name of your variable s ever changes, then the debugging messages will be updated as well, whereas if you just hardcode the name of the variable, then it will eventually be outdated when updates are made over time. It's a good practice used in the industry.

提交回复
热议问题