6

This is the first time I've really dealt with Expression Trees, and I am a bit lost. I apologise if this question just doesn't make any sense at all. Consider the following classes:

public class Foo<T> {
    public T Value { get; set; }
    public bool Update { get; set;}
}

public class Bar {
    public Foo<bool> SomeBool { get; set; }
    public Foo<string> SomeString { get; set; }
}

So right now I have a helper method that looks like this:

public void Helper<T>(Expression<Func<Bar, Foo<T>>> baseExpression, Expression<Func<Bar, T>> valExpression, Expression<Func<Bar, bool>> updateExpression) 
{
    // Do some stuff with those expressions.
}

And then it gets invoked like this:

Helper(b=>b.SomeBool,b=>b.SomeBool.Value,b=>b.SomeBool.Update);

But I dislike building three almost exact same expressions, and having to explicitly pass them into the Helper. What I would prefer is to something like this:

Helper(b=>b.SomeBool);

And then:

public void Helper<T>(Expression<Func<Bar, Foo<T>>> baseExpression) 
{
    // Do some stuff
    var valExpression = ???; // append `.Value` to baseExpression
    var updateExpression = ???; // append `.Update` to baseExpression
}

But I'm not really sure how to do that... Its boggling my mind, any shove in the right direction would be wildly appriciated.

J. Holmes
  • 18,466
  • 5
  • 47
  • 52

1 Answers1

7

Sure; if you have baseExpression, then something like:

var valExpression = Expression.Lambda<Func<Bar, T>>(
    Expression.PropertyOrField(baseExpression.Body, "Value"),
    baseExpression.Parameters);
var updateExpression = Expression.Lambda<Func<Bar, bool>>(
    Expression.PropertyOrField(baseExpression.Body, "Update"),
    baseExpression.Parameters);
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900