0

When I say Key, I'm referring to the "Keys" enum in Windows Forms. For instance:

I might have a string:

string key = "Q";

And I'm trying to convert it to this:

Keys.Q

How would I do this? (If even possible)

Yochran
  • 17
  • 1
  • 4

1 Answers1

1

In case that the values of the string are not exactly the same as the enum you can do it with a switch-case statment.

Keys keys = key switch
{
    "Q" => Keys.Q
    ...
};

If the values exactly the same just parse it:

public static TEnum ToEnum<TEnum>(this string strEnumValue)
{
    if (!Enum.IsDefined(typeof(TEnum), strEnumValue))
    {
        throw new Exception("Enum can't be parsed");
    }

    return (TEnum)Enum.Parse(typeof(TEnum), strEnumValue);
}

Keys keys = key.ToEnum<Keys>();
Misha Zaslavsky
  • 8,414
  • 11
  • 70
  • 116