Update: The code has moved to
NetFx project at http://code.google.com/p/netfx/source/browse/trunk/Source/Guard.cs .

In the task of validating function arguments, usually a sealed class Guard is created. For example, if we want to validate for null value the usual code is:

    public sealed class Guard
    {
        public static void ArgumentNotNull(object val, string argName)
        {
            if (val == null)
                throw new ArgumentNullException(argName);
        }
    }
    public class Bank
    {
        public void Transfer(Account source, Account destination, decimal amount)
        {
            Guard.ArgumentNotNull(source, "source");
            Guard.ArgumentNotNull(destination, "destination");
            // TODO ... actual founds transfer
        }
    }

I never like to pass the parameter and it’s name in the same argument call, specially because while refactoring, the argName argument won’t be changed by default.

To eliminate that hack, we could use GuardQ (C# 3.0), which will be consumed, for the same example of above as:

    public sealed class GuardQ
    {
        public static void ArgumentNotNull<TResult>(Expression<Func<TResult>> expression)
        {
            if (expression.Compile().Invoke() == null)
            {
                PrettyPrinter printer = new PrettyPrinter();
                string argName = printer.Print(expression.Body);
                throw new ArgumentNullException(argName);
            }
        }
    }
    public class Bank
    {
        public void Transfer(Account source, Account destination, decimal amount)
        {
            GuardQ.ArgumentNotNull(() => source);
            GuardQ.ArgumentNotNull(() => destination);
            // TODO ... actual founds transfer
        }
    }

Only one argument per validation: a lambda expression with no parameters and the parameter to validate in the body. From the expression’s body, using a kind of ExpressionPrinter we could get the argument name: hack removed!. And refactoring is 100% supported.

Since the ToString method of the body of () => source, would return something like “value(GuardQ.Tests.Demo+Bank+<>c__DisplayClass0).source”, I start to develop a PrettyPrinter, to get a string representation of the expression that the user input in the source code (currently, don’t printing the context nodes).In the following weeks some additions will appear, and a non-spike code would be available in MoQ.

Current source: https://moq.googlecode.com/svn/spikes/GuardQ/