Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a conversion method that takes a char and produces a ConsoleKey?

Tags:

c#

.net

I wonder if there is any helper class in the .NET framework (or somewhere else) that converts chars to ConsoleKey enums.

e.g 'A' should become ConsoleKey.A

Before someone asks why I would want to do that. I want to write a helper that takes a string (e.g. 'Hello World') and converts it into a sequence of ConsoleKeyInfo objects. I need this for some crazy unit tests where I'm mocking user input.

I'm just a little tired of creating glue code on my own so I thought, maybe there is already a way to convert a char to a ConsoleKey enum?

For completeness here is what seems to work great so far

    public static IEnumerable<ConsoleKeyInfo> ToInputSequence(this string text)
    {
        return text.Select(c =>
                               {
                                   ConsoleKey consoleKey;
                                   if (Enum.TryParse(c.ToString(CultureInfo.InvariantCulture), true, out consoleKey))
                                   {
                                       return new ConsoleKeyInfo(c, consoleKey, false, false, false);
                                   }
                                   else if (c == ' ')
                                       return new ConsoleKeyInfo(' ', ConsoleKey.Spacebar, false, false, false);
                                   return (ConsoleKeyInfo?) null;
                               })
            .Where(info => info.HasValue)
            .Select(info => info.GetValueOrDefault());
    }
like image 890
Christoph Avatar asked Jul 15 '12 19:07

Christoph


2 Answers

Have you tried:

char a = 'A';
ConsoleKey ck;
Enum.TryParse<ConsoleKey>(a.ToString(), out ck);

So:

string input = "Hello World";
input.Select(c => (ConsoleKey)Enum.Parse(c.ToString().ToUpper(), typeof(ConsoleKey));

or

.Select(c =>
    {
        return Enum.TryParse<ConsoleKey>(a.ToString().ToUpper(), out ck) ?
            ck :
            (ConsoleKey?)null;
    })
.Where(x => x.HasValue) // where parse has worked
.Select(x => x.Value);

Also Enum.TryParse() has an overload to ignore case.

like image 123
abatishchev Avatar answered Nov 04 '22 02:11

abatishchev


If you using .NET4 or later you can use Enum.TryParse. and Enum.Parse is avalable for .NET2 and later.

like image 1
Ria Avatar answered Nov 04 '22 03:11

Ria