Expression tree library and relationships between enums
In C #, I can successfully compare enum values using any relational operators as shown below:
var res = SomeEnumType.First < SomeEnumType.Second
When trying to accomplish the same with an 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 (similarly 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?
+3
source to share
2 answers
You need to convert the enum value to the enum type given below:
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));
+2
source to share