I know two ways to check parameters of the method and throw exceptions when it is needed.
1) Check one each parameter and throw an exception when it is wrong:
public void Method(object parameter1, object parameter2)
{
if (parameter1 == null)
{
throw new ArgumentNullException("parameter1");
}
if (parameter2 == null)
{
throw new ArgumentNullException("parameter2");
}
...
}
2) Check all parameters at once and throw same exception for all:
public void Method(object parameter1, object parameter2)
{
if (parameter1 == null || parameter2 == null)
{
throw new ArgumentNullException();
}
...
}
The first approach is, in my opinion, better and cleaner, but also cover a lot of lines. For example, a method that actually do the 2 lines of code – in this way code will increase by 4 rows (including blank line) for each parameter.
I am interested in is the approach used by experienced programmers. Are there better ways than these two?
Updated July 2020
Check out this blog post on how you can achieve a similar approach to Code Contracts.
https://enterprisecraftsmanship.com/posts/code-contracts-vs-input-validation/
Original answer provided below
—-
If you are using .NET framework 4, check out Code Contracts, which simplifies it down to a single line of code
The reason you would use this is because you can now get automated tools like Pex to tell you what unit tests to apply to this method. It also gives you feedback at compile time if this method would throw an exception based on how you are calling it. Like
The compiler will warn you that this will throw an exception.
Note Code Contracts needs an add-in to be installed, but it is free.