What is the best way to check the parameters of the method?
Use method attribute to cleanly check your parameters. i was wrote a framework for parameter validating in python.the c# best practice is here
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
public string Reverse(string text)
{
Contract.Requires<ArgumentNullException>(text!=null, "ParAmeter cannot be null.");
.....
}
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
String text = null;
String reversedString = Reverse(text);
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.
Approach 1 is significantly more useful in my opinion. NullReferenceException
s, or in this case ArgumentNullException
s thrown where you can't determine what was null
is very frustrating.
Also, if you don't like looking at the validation code you can always wrap it in a code region and fold it away in your IDE.