I hate using strings to represent program elements!  One of the big problems is that it hinders automated refactoring.  Strings don’t have any semantic meaning, so refactoring tools don’t know which references to the string need to be updated.

 

While playing with expression trees, a while ago I came up with this:

public static class Argument
{
    public static void NotNull(object value, Expression<Func<Func<object>>> arg)
    {
        if (value == null)
        {
            var body1 = (Expression<Func<object>>)arg.Body;
            var body2 = (MemberExpression)body1.Body;
            throw new ArgumentNullException(body2.Member.Name);
        }

    }
}

 

You can use this for argument validation like this:

static void Main(string[] args)
{
    Argument.NotNull(args, () => () => args);
}

 

This looks a little strange, but has some interesting properties:

  1. There are no strings, which means that refactoring tools “Just Work” and update all references.
  2. The majority of the reflection code happens only in the exception code, which means that this has significantly better performance than my first attempt (which took just an “Expression<Func<object>>”

On the other hand it has some drawbacks too:

  1. The calling side looks a little strange with “() => () =>'”
  2. Using this approach will lead to a LOT of compiler generated display classes to store the parameter references.

I’m not sure I would use this in production code, but it was an interesting exercise to come up with a way of validating parameters that doesn’t involve strings.

 

What do you think?