Search code examples
c#-4.0expression-trees

How can I assign a variable from a static property using Expression Trees?


Given a ParameterExpression of type DateTime, how do I generate an expression tree to assign DateTime.Now.Date to this variable?

var x = Expression.Parameter(typeof(DateTime), "now");
var dateTimeNow = ... ? // What goes on this line?
var assignment = Expression.Assign(x, dateTimeNow);

I want the result of the assignment to be the value of DateTime.Now.Date when the resultant expression is invoked, not at compile-time.


Solution

  • var dateTimeNow = Expression.Property(
        Expression.Property(null, typeof(DateTime).GetProperty("Now")),
        "Date");