Search code examples
c#expression-trees

Create Action to assign property from name of a property provided by string


What I'm trying to achieve is to create Action to assign a value to the object property defined by a string. What i have come up with so far is:

void Main()
{
    var startPropertyName= "StartTime";
    var endPropertyName= "EndTime";


    var myAction = AssignValueToProperty<MyClass>(startPropertyName, DateTime.Today);

    var myObject = new MyClass();
    myAction(myObject);
    myObject.StartTime.Dump();

}

public static Action<T> AssignValueToProperty<T>(string propertyName, DateTime value)
{
    var arg = Expression.Parameter(typeof(T));
    var property = Expression.Property(arg, propertyName);

    var cons = Expression.Constant(value, typeof(DateTime));

    var body = Expression.Assign(property, cons);
    var exp = Expression.Lambda<Action<T>>(body, new ParameterExpression[] { arg });
    return exp.Compile();
}

public class MyClass
{
    public DateTime StartTime { get; set; }
    public DateTime EndTime { get; set; }
}

But i would like to pass the DateTime parameter during calling the Action not during creating it. And possibly add another parameter for EndTime Property.


Solution

  • You were most of the way there. Just declare another ParameterExpression for your new parameter.

    public static Action<T, DateTime> AssignValueToProperty<T>(string propertyName)
    {
        var arg = Expression.Parameter(typeof(T), "arg");
        var startTime = Expression.Parameter(typeof(DateTime), "startTime");
        var property = Expression.Property(arg, propertyName);
    
        var body = Expression.Assign(property, startTime);
        var exp = Expression.Lambda<Action<T, DateTime>>(body, new ParameterExpression[] { arg, startTime });
        return exp.Compile();
    }