Using LINQ expressions to name Validation Rules
02 Mar 2008 by Nigel SampsonIn various places in code we want to use property names in our code, for instance validation or business rules are quick commonly named after the property they're validating. Usually you end up with code looking a little like this.
Rule<Person> rule = new Rule<Person>("FirstName");
As Ayende says "Strings are bad", there are typo issues and also they're immune to refactoring. So here's a quick way not to use them, I wouldn't call this fully fledged as we're not getting compile time checking yet. The key part to this code is taking an Expression rather than a Func, this allows us to examine the expressions in the lambda to get the property name.
public class Rule<T>
{
private string name;
public Rule(Expression<Func<T, object>> expression)
{
MemberExpression memberExpression = expression.Body as MemberExpression;
name = memberExpression == null ? String.Empty : memberExpression.Member.Name;
}
public string Name
{
get
{
return name;
}
}
}
This gives the syntax for rule creation as follows.
Rule<Person> rule = new Rule<Person>(p => p.FirstName);