CSharp > Property getter expression does not work with Condition

I've got the following Code:

    public static Func<object, string> GetPropGetter(Type objectType, string propertyName)
    {
        ParameterExpression paramExpression = Expression.Parameter(typeof(object), "value");

        Expression e = Expression.Convert(paramExpression, objectType);

        foreach (var name in propertyName.Split('.'))
        {
            e = Expression.Property(e, name);
        }

        Expression propertyGetterExpression = Expression.Call(e, typeof(object).GetMethod("ToString", Type.EmptyTypes));

        Func<object, string> result =
            Expression.Lambda<Func<object, string>>(propertyGetterExpression, paramExpression).Compile();

        return result;
    }

This works if the Property is not null. For this check I changed the Code to:

    public static Func<object, string> GetPropGetter(Type objectType, string propertyName)
    {
        ParameterExpression paramExpression = Expression.Parameter(typeof(object), "value");

        Expression e = Expression.Convert(paramExpression, objectType);

        foreach (var name in propertyName.Split('.'))
        {
            e = Expression.Property(e, name);
        }

        Expression propertyGetterExpression = Expression.IfThenElse(Expression.Equal(Expression.Default((e as MemberExpression).Type), e), Expression.Constant(""), Expression.Call(e, typeof(object).GetMethod("ToString", Type.EmptyTypes)));


        Func<object, string> result =
            Expression.Lambda<Func<object, string>>(propertyGetterExpression, paramExpression).Compile();

        return result;         
    }

Now I got the Exception: ArgumentException, the Expression of Type void could not be used for the return value of string!

Jon Skeet
people
quotationmark

It may not be the only thing that you need to do, but I think you want to use Expression.Condition rather than Expression.IfThenElse.

Currently you've got the equivalent of:

if (condition) {
    default(...);
} else {
    property-getters
}

without any return. (As noted in the documentation, the overall type of the expression returned by IfThenElse is Void.)

You really want:

return condition ? default(...) : property-getters;

The latter is what Expression.Condition represents.

people

See more on this question at Stackoverflow