2

How one can assign the following statement using expression Tree

myFoo.myBar = new Bar();

My Code is as follows -

    public static Action<TObject, TProperty>CreateNewObjectAndSet<TObject,TProperty>(string propertyName)
    {

        ParameterExpression paramExpression = Expression.Parameter(typeof(TObject));
        MemberExpression propertyGetterExpression = Expression.Property(paramExpression, propertyName);

        var newObject = Expression.New(typeof(TProperty));

        var x = Expression.Assign(propertyGetterExpression, newObject);

        var paramExpressions = new ParameterExpression[2];
        paramExpressions[0] = paramExpression;
        paramExpressions[1] = newObject;

        Action<TObject, TProperty> result = Expression.Lambda<Action<TObject, TProperty>>(x, paramExpressions).Compile();

        return result;
    }

Compile error occurs at the statement

paramExpression[1] = newObject;

1 Answer 1

1

Since target expression is:

myFoo.myBar = new Bar();

you don't need 2 parameters, you only need 1 - instance of myFoo to set property on. So change your code like this:

public static Action<TObject> CreateNewObjectAndSet<TObject, TProperty>(string propertyName) where TProperty: new() {

    ParameterExpression paramExpression = Expression.Parameter(typeof(TObject));
    MemberExpression propertyGetterExpression = Expression.Property(paramExpression, propertyName);

    var newObject = Expression.New(typeof(TProperty));

    var x = Expression.Assign(propertyGetterExpression, newObject);

    var paramExpressions = new ParameterExpression[1];
    paramExpressions[0] = paramExpression;

    Action<TObject> result = Expression.Lambda<Action<TObject>>(x, paramExpressions).Compile();

    return result;
}

Then call like this:

var setter = CreateNewObjectAndSet<Foo, Bar>("myBar");
setter(myFoo);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.