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.