Home > Software design >  Getting ToString method of an enum
Getting ToString method of an enum

Time:04-08

I am trying to get the ToString method of an enum like this

  var parameterExpression = Expression.Parameter(typeof(Program), "x");
  var toStringMethod = typeof(Enum).GetMethod("ToString", new Type[0]);
  Expression leftExpression = Expression.Call(property, toStringMethod);

but this is returning null when passing it.

CodePudding user response:

You're saying that you want a method on Enum called ToString which has a single parameter of type Enum.

But that's not the signature of Enum.ToString. Enum.ToString has the following overloads:

string ToString();
string ToString (string? format);
// and two obsolete overloads

Look for the correct parameter types, and you're fine:

var toStringMethod = typeof(Enum).GetMethod("ToString", new Type[0]);

or:

var toStringMethod = typeof(Enum).GetMethod("ToString", new[] { typeof(string) });
  • Related