FxCop can drive you crazy, but ... It improves the quality of your code!
Tip: enable the Code Analysis in the beginning!
I am sure that you have ever seen the following FxCop warning:
Microsoft.Design --> CA1062:ValidateArgumentsOfPublicMethods
This article gives you a uniform way of validating parameters!
1. Validating parameters in every public method
If you have to check every parameter every public method. This means that you add at least 3 lines ...
if( condition )
// exception statement;
- Re-writing code every time you need to check parameters
- 3 lines of code extra in every public method which has parameters.
2. Using the ParameterCheck class for Parameter validations
You can reduce the 3 lines of code into 1 line. Just make a separate Visual Studio Project which is responsable to check parameters. It is a static class which has static methods.
ParameterCheck Method Overview
Checks if a string is empty or null
Checks when an object is null. In case of a DateTime object, it cannot be the MinValue (which will be compared with null)
- WithinRange (for int)
Checks if the Int value (16/32/64 bit) has a value within the range (ranges inclusive)
- WithinRange (for double)
Checks if the decimal value (decimal, single, float, double) has a value within the range (ranges inclusive)
- WithinRange (for DateTime)
Checks if the DateTime value has a value within the range (ranges inclusive)
- BiggerOrEquals (for int)
Checks if a number has a value which is bigger or equals to the minimum value (minimum value included)
- SmallerOrEquals (for int)
Checks if a number has a value which is smaller or equals to the maximum value (maximum value included)
public static void NotNullOrEmpty(string parameterName, string parameterValue)
throw new ArgumentNullException(parameterName);
- Just 1 line of code!
- Same result
- FxCop/Code Analysis does not recognize your class as being a valid parameter validation. You should add a SuppressMessage (right-click on the warning in the error list and select 'suppress message')
You can download the code of this article here.