Easy Easy - 3 months ago 23
C# Question

How to check if any of 2 possible keys is pressed with ConsoleKeyInfo?

I encountered a pretty dumb problem with ConsoleKeyInfo. I want do check if "1" is entered using either numpad or regular top numeric keys.

ConsoleKeyInfo keyPressed;
keyPressed = Console.ReadKey();
if (keyPressed = ConsoleKey.D1 || keyPressed = ConsoleKey.NumPad1)
{ }

And for some reason I cant use "||" operator. Is it possible to somehow check it within 1 if loop without using
and forcing user to press enter?


You have to compare with == instead of =. Otherwise you're trying to assigning the value.

And you have to compare the Key property of ConsoleKeyInfo which holds the ConsoleKey enum.

So your if should look like:

if (keyPressed.Key == ConsoleKey.D1 || keyPressed.Key == ConsoleKey.NumPad1)