Search code examples
c#.net-corereflectiontype-conversionsystem.linq.dynamic

DynamicExpressionParser parse expression for enum property as integer


I want to create an expression for converting a property from an Enum to an Int. I want to use DynamicExpressionParser.ParseLambda to parse nested properties:

public enum MyEnum { A, B };

public class OuterClass
{
    public InnerClass Inner { get; set; }

    public MyEnum Enum { get; set; }
}

public class InnerClass
{
    public MyEnum Enum { get; set; }
}

DynamicExpressionParser.ParseLambda<OuterClass, int>(null, true, "Inner.Enum");

But this will throw an exception: Expression of type 'Int32' expected (at index 0)

How can I convert the Enum to an integer inside the expression?

It works with the following method, but i cannot use nested properties there, so it will only work when I place the "Enum" property on the OuterClass:

public static Expression<Func<T, TProperty>> GetExpression<T, TProperty>(string propertyName)
        {
            // x =>
            var parameter = Expression.Parameter(typeof(T));
            // x.Name
            var mapProperty = Expression.Property(parameter, propertyName);
            // (object)x.Name
            var convertedExpression = Expression.Convert(mapProperty, typeof(TProperty));
            // x => (object)x.Name
            return Expression.Lambda<Func<T, TProperty>>(convertedExpression, parameter);
        }

 GetExpression<OuterClass, int>("Enum");

Solution

  • I found a solution:

    // Create expression for it-type OuterClass. Pass null for result type which will result in an expression with the result type of the actual enum type.
    var enumExpression = DynamicExpressionParser.ParseLambda(typeof(OuterClass), null, "Inner.Enum");
    
    // Convert the result type of the body to int which will result in a converted expression
    var convertedBodyExpression = Expression.Convert(enumExpression.Body, typeof(int));
    
    // Create the final expression
    var expression = Expression.Lambda<Func<OuterClass, int>>(convertedBodyExpression, enumExpression.Parameters);