Search code examples
c#.netcompiler-errorsconsole-application

C# Error Cannot implicitly convert type 'System.ConsoleKey' to 'char'


The following C# code I wrote gives me an error:

switch (Console.ReadKey(true).KeyChar)
{
    case ConsoleKey.DownArrow:
        Console.SetCursorPosition(x, y);
        break;
}

The error:

Error 1 Cannot implicitly convert type 'System.ConsoleKey' to 'char'. An explicit conversion exists (are you missing a cast?)

What's wrong?


Solution

  • You should use the Key property instead of the KeyChar property.

    switch (Console.ReadKey(true).Key)
    {
        case ConsoleKey.DownArrow:
            Console.SetCursorPosition(x,y);
            break;
    }
    

    The constant ConsoleKey.DownArrow is of type ConsoleKey, while Console.ReadKey(true).KeyChar is of type char.

    Since char and ConsoleKey are different types, this code can't compile.

    Instead, if you use the Key property of the ReadKey return value, you get a ConsoleKey, which is of the same type as the cases in the switch statement.