views:

113

answers:

1

I Have a quite simple question that I just cant figure out.

The method code is simple:

protected void Require<TValidator, TParam>(TValidator validator, Expression<Func<TValidator, TParam>> property, Predicate<TParam> predicate)
{
    var propertyValue = property.Compile().Invoke(validator);
    if(!predicate.Invoke(propertyValue))
        throw new ValidatorInitializationException("Error while initializing validator", GetType());
}

The problem is that I would like to pack more info into the error message. Getting information out of the expression is easy. But how can I get to a "user friendly" string representation of the predicate?

+1  A: 

You'd have to accept that as an expression tree too:

protected void Require<TValidator, TParam>(
    TValidator validator, 
    Expression<Func<TValidator, TParam>> property, 
    Expression<Predicate<TParam>> predicateExpression)
{
    var propertyValue = property.Compile().Invoke(validator);
    Predicat<TParam> predicate = predicateExpression.Compile();        
    if(!predicate.Invoke(propertyValue))
    {    
        throw new ValidatorInitializationException(
            "Error while initializing validator: " + predicateExpression,
            GetType());
    }
}
Jon Skeet