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
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.