Search code examples
c#lambdaexpression-trees

Expression.Convert type for Expression.Property


I'm trying to convert a Parameter expression and having trouble with converting to value types. Below is a sample of my code:

public static MemberExpression ConvertToType(ParameterExpression sourceParameter,
                                              PropertyInfo propertyInfo, 
                                              TypeCode typeCode)
{
    var sourceExpressionProperty = Expression.Property(sourceParameter, sourceProperty);

    //throws an exception if typeCode is a value type.
    Expression convertedSource = Expression.Convert(sourceExpressionProperty,
                                                Type.GetType("System." + typeCode));

    return convertedSource;
}

I get the following invalid operation exception:

No coercion operator is defined between types 'System.String' and 'System.Decimal'.

Any help with this conversion would be greatly appreciated.


Solution

  • The solution I went with was:

    private static Expression GetConvertedSource(ParameterExpression sourceParameter,
                                                 PropertyInfo sourceProperty, 
                                                 TypeCode typeCode)
    {
        var sourceExpressionProperty = Expression.Property(sourceParameter,
                                                           sourceProperty);
    
        var changeTypeCall = Expression.Call(typeof(Convert).GetMethod("ChangeType", 
                                                               new[] { typeof(object),
                                                                typeof(TypeCode) }),
                                                                sourceExpressionProperty,
                                                                Expression.Constant(typeCode)
                                                                );
    
        Expression convert = Expression.Convert(changeTypeCall, 
                                                Type.GetType("System." + typeCode));
    
        var convertExpr = Expression.Condition(Expression.Equal(sourceExpressionProperty,
                                                Expression.Constant(null, sourceProperty.PropertyType)),
                                                Expression.Default(Type.GetType("System." + typeCode)),
                                                convert);
    
    
    
        return convertExpr;
    }
    

    Note the Expression.Condition to handle nulls.