Only allow 2 chars to be input in a console application

ddanbe 0 Tallied Votes 249 Views Share

Many situations arise when you have to choose between two options: true/false, male/female etc.
This short snippet will only allow two chars to pass through: capital 'Y' or capital 'N'.
The Read and ReadLine methods can serve also, but have the side effect you have to use Upper and Lower case methods if-statements, or (with ReadLine) testing if only 1 char is input etc.
Notice that the condition in the do - while has to be false.

ConsoleKeyInfo K;
            Console.WriteLine("Would you like to start? (Type Y or N)");
            do
            {
                K = Console.ReadKey();
            } while (K.KeyChar != 'Y' && K.KeyChar != 'N');