Search code examples
c#.netenumsexpression-trees

Expression tree library and relations between enums


In C# I can successfully compare enum values using any relational operators, like below:

var res  = SomeEnumType.First < SomeEnumType.Second

While trying to accomplish the same using expression library:

var arg1 = Expression.Constant(SomeEnumType.First);
var arg2 = Expression.Constant(SomeEnumType.Second);
var res  = Expression.LessThan(arg1, arg2);

the following error is thrown (analogically for <=, > and >=):

The binary operator LessThan is not defined for the types 'Prog.SomeEnumType' and 'Prog.SomeEnumType'.

What is the correct way to fix it?


Solution

  • You have to convert enum value to the enum underlying type:

    var arg1 = Expression.Constant(SomeEnumType.First);
    var arg2 = Expression.Constant(SomeEnumType.Second);
    var enumType = Enum.GetUnderlyingType(typeof (SomeEnumType));
    var res = Expression.LessThan(Expression.Convert(arg1, enumType), Expression.Convert(arg2, enumType));