In order for the console to filter out alphanumeric keystrokes, you must take care of the input. The Console.ReadKey () method is fundamental for this; it allows you to sniff the key pressed. Here is an example implementation:
static string ReadNumber() { var buf = new StringBuilder(); for (; ; ) { var key = Console.ReadKey(true); if (key.Key == ConsoleKey.Enter && buf.Length > 0) { return buf.ToString() ; } else if (key.Key == ConsoleKey.Backspace && buf.Length > 0) { buf.Remove(buf.Length-1, 1); Console.Write("\b \b"); } else if ("0123456789.-".Contains(key.KeyChar)) { buf.Append(key.KeyChar); Console.Write(key.KeyChar); } else { Console.Beep(); } } }
You can add, say, Decimal.TryParse () to an if () statement that detects the Enter key to verify that the string you entered is still a real number. Thus, you can reject input of type "1-2".
Hans passant
source share