Most of the functions take some input parameters and it is mostly wise not to trust the caller and do verification of input parameters. Input parameter validation involves checking some constraint for the parameter (like parameter is null or not, parameter value falls in some range or not, etc). If the constraint does not meet, the code generally throws exception. The most common exceptions are ArgumentNullException and ArgumentException.
A typical function with multiple if-check-throw pattern looks something like this:
public class MyClass
public void MyFunction(Foo firstParam, Bar secondParam)
if (firstParam == null)
Logger.LogMessage("firstParam is passed is null which is unexpected");
throw new ArgumentNullException("firstParam", "firstParam is passed is null which is unexpected");
if (secondParam == null)
Logger.LogMessage("Null value for Bar instance is not allowed");
throw new ArgumentNullException("secondParam", "Null value for Bar instance is not allowed");
// Do something
Multiple repetitive comparisons are mostly not very interesting to write/read.
Here is a method to do null parameter validation using extension method.
This extension method is based on the fact that an extension method can be called even on a null instance of a class. In other words, the method call on a null instance of a class results in NullReferenceException. But calling an extension method on null instance of a class is perfectly fine.
The extension method for parameter validation is as follows:
public static class ParameterExtensions
public static void ThrowIfNull(this object instance, string paramName, string message, params object parameters)
if (instance == null)
throw new ArgumentNullException(paramName, string.Format(message, parameters));
This extension function is written for System.object class, so it is applicable for any class. It checks for input parameter and if it null it throws ArgumentNullException. Depending on the usage, more parameters can be added to the function to give a meaningful error message to the caller (like parameter name or some error message).
The usage of the method is much simpler than the if-throw pattern:
public class MyClassWithExtensionMethod
firstParam.ThrowIfNull("firstParam", "firstParam is passed is null which is unexpected");
secondParam.ThrowIfNull("secondParam", "Null value for Bar instance is not allowed");
There are other approaches also to do it which are definitely better than the if-check-throw like Code contracts.
You can definitely use Contracts here. .NET 4.0 supports them off the box in System.Diagnostics.Contracts. Check this: msdn.microsoft.com/.../system.diagnostics.contracts.aspx