Property selector Expression. How to get/set value to selected property

The parameter would be an Expression<Func<Customer,string>> selector. Reading it can be via flat compile:

 Func<Customer,string> func = selector.Compile();

then you can access func(customer). Assigning is trickier; for simple selectors your could hope that you can simply decompose to:

var prop = (PropertyInfo)((MemberExpression)selector.Body).Member;
prop.SetValue(customer, newValue, null);

But more complex expressions would either need a manual tree walk, or some of the 4.0 expression node-types:

        Expression<Func<Customer, string>> email
             = cust => cust.Email;

        var newValue = Expression.Parameter(email.Body.Type);
        var assign = Expression.Lambda<Action<Customer, string>>(
            Expression.Assign(email.Body, newValue),
            email.Parameters[0], newValue);

        var getter = email.Compile();
        var setter = assign.Compile();

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)