Search code examples
c#.netreflectionenumsexpression-trees

Assignment expression that sets a dynamically-created enum value


I have the following enumeration:

[Flags]
public enum MyEnum
{
    None = 0,
    Value1 = 1,
    Value2 = 2,
}

This enumeration has been dynamically created using the TypeBuilder so there is no compile-time reference to it as a strongly-typed enumeration.

// The variable enumBuilder is fully created and ready for use.
var code = Expression.Variable(enumBuilder, "code");

I now need to assign MyEnum.Value2 to the variable code.

// The following line is supposed to do this: code = MyEnum.Value2;
var assign = Expression.Assign(code, ?????);

How do I create the right side of the expression that would evaluate to MyEnum.Value2?


Solution

  • Type enumType = enumBuilder.CreateType();
    var assign = Expression.Assign(code, Expression.Constant(2, enumType));