How to generate dynamic expression with bitwise operator and enumerations?

Say I have the following listing.

[Flags] public enum Color { Red = 1, Blue = 2, Green = 4 } 

Now I want to use the following query to find Red shirts.

 Shirts.Where(x => (x.Color & Color.Red) != 0) 

And this works fine, but when I try to build it dynamically:

 var color= Expression.Constant(Color.Red); var property = Expression.Property(Expression.Parameter(typeof(Shirt)), "Color"); Expression.NotEqual(Expression.And(property, color), Expression.Constant(0)); 

I get the following exception:

Binary operator A is not defined for the types "MyEnums.Color" and "MyEnums.Color".

I am using .NET 4.5

Any thoughts?

+6
source share
1 answer

Try converting the color and property to the base type using Expression.Convert :

 var color= Expression.Constant(Color.Red); var property = Expression.Property(Expression.Parameter(typeof(Shirt)), "Color"); var colorValue = Expression.Convert(color, Enum.GetUnderlyingType(typeof(Color))); var propertyValue = Expression.Convert(property, Enum.GetUnderlyingType(typeof(Color))); Expression.NotEqual(Expression.And(propertyValue, colorValue), Expression.Constant(0)); 
+8
source

All Articles