Search code examples
c#reflectionexpressionexpression-treesfunc

Implementing Binding Paths


Trying to implement a field binding system and I have the following method:

    public void SetValue<TField>(Expression<Func<TField>> field, object value)
    {
        ((field.Body as MemberExpression).Member as FieldInfo).SetValue(this, value);

        // check bindings etc.
    }

That is used like this:

    myObj.SetValue(() => myObj.SomeStringField, "SomeString");

It works as intended, the value is set and I can do some other stuff I want like checking bindings etc.

Now I'm trying to implement support of binding paths, i.e. allow for something like:

    myObj.SetValue(() => myObj.Names[1].FirstName, "John");

I got the FieldInfo of FirstName but now I also need to (at least) get the reference to the object myObj.Names[1] from the expression. Any ideas on how to do this?


Solution

  • A general approach would be to create an expression that assigns the value to your expression:

    public static void SetValue<TField>(Expression<Func<TField>> field, TField value)
    {
        var expression = Expression.Lambda<Action>(
            Expression.Assign(field.Body, Expression.Constant(value)));
        expression.Compile()();
    }