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?
You should use the
Keyproperty instead of theKeyCharproperty.The constant
ConsoleKey.DownArrowis of typeConsoleKey, whileConsole.ReadKey(true).KeyCharis of typechar.Since
charandConsoleKeyare different types, this code can’t compile.Instead, if you use the Key property of the
ReadKeyreturn value, you get aConsoleKey, which is of the same type as the cases in the switch statement.