Alex Rivera | Logout

when and in what scenario to use Expression Tree

Asked 2010-08-20T06:18:54.397
13

I was reading about Expression Tree feature and how you can create delegates using lambda expressions. I still can't get as to in what scenario it is useful and in what real world example should I use it.

Edit
Report

1 Answer

5

Aside from LINQ, another very simple use case is to extract both the name and the value of a property. I use this in a fluent API for validating data transfer objects. It's safer to pass one lambda parameter to define both name and value rather than have a second string parameter for the name, and run the risk of developers getting it wrong.

Here's an example (minus all the safety checks and other housekeeping):

public Validator<T> Check<T>(Expression<Func<T>> expr) {
    // Analyse the expression as data
    string name = ((MemberExpression) expr.Body).Member.Name;
    // Compile and execute it to get the value
    T value = (expr.Compile())();
    return new Validator<T>(name, value);
}

Example of use:

Check(() => x.Name).NotNull.MinLength(1);
Check(() => x.Age).GreaterThan(18);
answered 2010-08-20T07:49:55.540

Your Answer