My first advice to you is get ReSharper. It will tell you when there is a problem of possible null values, and when there is no need to check for them, and with the click of a mouse will add checking. Having said that...
You don't have to check for int or bool, which cannot be null.
Strings can be checked with string.IsNullOrEmpty()...
If you still decide that you want to check each and every parameter, you can either use the Command design pattern, and reflection, but your code will be unnecessarily clunky, or use the following and call it for each method: private myType myMethod(string param1, int param2, byte[] param3) { CheckParameters("myMethod", {param1, param2, param3}); // rest of code...
And in your utility class put this:
///<summary>Validates method parameters</summary> ///... rest of documentation public void CheckParameters(string methodName, List<Object> parameterValues) { if ( string.IsNullOrEmpty(methodName) ) throw new ArgumentException("Fire the programmer! Missing method name", "methodName")); Type t = typeof(MyClass); MethodInfo method = t.GetMethod(methodName); if ( method == null ) throw new ArgumentException("Fire the programmer! Wrong method name", "methodName")); List<ParameterInfo> params = method.GetParameters(); if ( params == null || params.Count != parameterValues.Count ) throw new ArgumentException("Fire the programmer! Wrong list of parameters. Should have " + params.Count + " parameters", "parameterValues")); for (int i = 0; i < params.Count; i++ ) { ParamInfo param = params[i]; if ( param.Type != typeof(parameterValues[i]) ) throw new ArgumentException("Fire the programmer! Wrong order of parameters. Error in param " + param.Name, "parameterValues")); if ( parameterValues[i] == null ) throw new ArgumentException(param.Name + " cannot be null"); } } // enjoy
nameofbuilt-in to get the name of your argument:if (foo == null) throw new ArgumentNullException(nameof(foo));. This pattern is useful in most of the answers below.