Search code examples
c#reflectionlambdaexpression-trees

ExpressionTree - GetSetMethod Error: Method 'System.String get_Name()' is not defined for type 'System.String'


Here is my method:

    public static MethodCallExpression ClonePropertyAssignmentLambda<T>(Expression source, string property)
    {
        var targetExp = Expression.Parameter(typeof (T), "target");
        var propertyInfo = typeof (T).GetProperty(property);
        var targetProperty = Expression.Property(targetExp, propertyInfo);
        var sourceProperty = Expression.Property(source, propertyInfo);

        return Expression.Call(targetProperty, ((PropertyInfo) targetProperty.Member).GetSetMethod(), sourceProperty);
    }

Here is how I'm calling it:

ClonePropertyAssignmentLambda<Person>(source, "Name")

I'm getting the error on the Expression.Call line. I get a similar error if I call GetGetMethod.


Solution

  • You're trying to get the Name property of a string object.

    Change it to

    return Expression.Call(targetExp, propertyInfo.GetSetMethod(), sourceProperty);