oku
oku

Reputation: 13

String (not just letter) to ConsoleKey c#

So i need to convert string to ConsoleKey...

Yes something like this works:

string ch = "a";
ConsoleKey ck = (ConsoleKey)Convert.ToChar(ch);

But what if the string is like "UpArrow" (the string is from ReadKey input and saved to txt file)

Please help.

Upvotes: 1

Views: 101

Answers (1)

Drew Noakes
Drew Noakes

Reputation: 311335

You can convert a string to an enum member using Enum.Parse or Enum.TryParse.

Unfortunately the API is not generic, so you have to specify the type a few times:

ConsoleKey key1 = (ConsoleKey)Enum.Parse(typeof(ConsoleKey), "UpArrow");

The above will throw an exception if the string is not a member of the enum. To protect against that you could use:

if (Enum.TryParse("UpArrow", out ConsoleKey key2))
{
    // use 'key2' in here
}

Upvotes: 2

Related Questions