Search code examples
c#enumsexpression-trees

How do you create an Expression of an enum from its type and the name of one of its fields?


Had a hard time finding what I'm trying to do and this post was the closest I could find. This post won't work as I don't know the integer value of the enum, I only know its name. Given the following code:

public enum Foo 
{
    Row = 0,
    Column = 20, // This is why the second post won't work, I only know the name "Column"
    None = 30
}

public static class ExpressionGetter
{
    public static Expression GetExpression(Type type, string name)
    {
        // Not sure what I should do here. I want an expression object for Foo.Row
    }
}

void Main()
{
   var expression = ExpressGetter.GetExpression(typeof(Foo), "Row");
}

Later in my application, I am building expression trees to generate LINQ queries and I know the type of the enum and name of the enum and now I want to create an Expression.Constant of it or if there's another way to do this, I'd like to know how.

I want at the end an expression that looks like this:

Foo.Row

I've tried:

Expression.Property(null, enumType, name)

But it does not work. Results in

ArgumentException: Property 'Row' is not defined for type 'Foo' Parameter name: propertyName

which makes sense because it's a struct not an object.

So I'm not sure how to build the Expression Foo.Row given the enum type Foo and the name as a string.


Solution

  • An enum value is a static field of the enum type. If you only have the name of the enum value as a string, the second version is what you're looking for. But you could also do Enum.Parse() with the first version.

    Expression.Constant(Foo.Row, typeof(Foo));
    
    //  Or any other string that's valid
    var name = "Row";
    MemberExpression.Field(null, typeof(Foo), name);