Help with KeyboardUtility class

WB1975

Well-known member
Joined
Apr 3, 2020
Messages
87
Programming Experience
Beginner
I thought it might be a good idea to have a class that handles all the keyboard stuff so i dont have to keep writing input code over and over i mean thats one of the pros i read about OOP, reusable code.

I have created a Class called KeyboardUtility and I have it returning number only input when the function is called.

I'm just wondering if im on the right track as usual, or whether this should be done another way.

I only have one function, but want to add like 1 to 4 menu, or y / n question or letters only etc etc

any ideas/advice would be accepted with arms wide open!!!

C#:
using System;
using System.Collections.Generic;
using System.Text;

namespace FootballLeague
{
    class KeyboardUtility
    {

        public static int NumberOnlyInput(string askForNumbers)
        {
            bool finishedEnteringNumbers = false;
            string userInput;
            int userNumberReturned;

            while (!finishedEnteringNumbers)
            {
                Console.WriteLine(askForNumbers);
                userInput = Console.ReadLine();
                bool isNumeric = int.TryParse(userInput, out userNumberReturned);
                if (isNumeric)
                {
                    return userNumberReturned;
                }
                else
                    {
                        Console.WriteLine("That is not a valid number...");
                    }
            }
            return 0;
        }
    }
}
 
No. The variable ch is set to be the uppercase version of the key that the user presses. Execution will go to lines 11 and 12 if the user presses Y or N. ch == 'Y' will be true if the user pressed Y.
 
oh right its only returning true with capital Y

lol didnt notice before how cool it is, it only allows input of y or n...very cool!
 
do you mind if i break down this method line by line im having a few problems understanding it all
If it's still on the topic of this thread, ask whatever you like.
 
static bool GetYesNo(string prompt) - creates a Method with the return type of boolean and takes in a string

Console.Write($"{prompt} [Y/N]: "); - Writes out to the console, though I dont know why $"{prompt} is used instead of just prompt + " [Y/N]: "

while (true) - a while loop that just keeps repeating everything in it while true, which it is

char ch = Console.ReadKey(true).KeyChar; - a character variable (char) named ch which equals a read in that I dont understand

I will stop at this first line I dont understand here

what is the best documentation to look up stuff like this? its obviously at Microsoft right?

i want to see if I can research the Console class and see the methods and how this works, will report back soon enough with more questions no doubt.
 
You can click to follow documentation for return type ConsoleKeyInfo.
 
Oh. I see the bug that the OP was referring too...
C#:
char ch = Console.ReadKey(true).KeyChar;
switch (char.ToUpper(ch))
should be:
C#:
char ch = Console.ReadKey(true).KeyChar;
ch = char.ToUpper(ch);
switch (ch)
Good catch!
 
Console.Write($"{prompt} [Y/N]: "); - Writes out to the console, though I dont know why $"{prompt} is used instead of just prompt + " [Y/N]: "
Many people consider using string interpolation to be more readable than using concatenation operators and you can count me amongst them. When it would only be two substrings being concatenated, you're getting into the area of personal preference but two or more and it's definitely less noisy. If you use it every time then you're being consistent and consistency is a good thing.
while (true) - a while loop that just keeps repeating everything in it while true, which it is
An infinite loop, i.e. one that you have to break out of explicitly, either with a return or break statement.
char ch = Console.ReadKey(true).KeyChar; - a character variable (char) named ch which equals a read in that I dont understand
You're only interested in one character so it makes sense to read one key. Not much point calling ReadLine and allowing the user to enter an essay that can't be valid. The ConsoleKeyInfo returned by ReadKey provides similar key and character information to the KeyDown and KeyPress events in WinForms. KeyChar is the character represented by the key or key combination the user pressed, which is what you are specifically interested in.
what is the best documentation to look up stuff like this? its obviously at Microsoft right?
You can click a type or member in the code window and press F1 to be taken directly to the relevant documentation. You can open the general documentation page from the Help menu in VS. You can access various areas of documentation there but the one I use most often is the API documentation. I have a direct link to that on the favourites bar in my browser:


That's the Australian version, so you may want to change the location.
 
char ch = Console.ReadKey(true).KeyChar; - a ch character variable that stores the KeyChar value when its pressed?

switch (char.ToUpper(ch)) - start of a switch that always converts the ch variable to upper case so if the user enters y or Y Y is always used

now this i dont get:

C#:
case 'Y':
            case 'N':
                Console.WriteLine(ch);
                return ch == 'Y';

Case Y do nothing???

Case N write out the ch variable
and return the variable as Y, shouldnt it be N?
 
Case Y do nothing???
Nope. A case without a break shares the body of the next case. That's how you do the same thing for multiple cases without repeating the same code multiple times. That means that the Console.WriteLine and the return are executed for both "Y" and "N" cases.
 
oh and

return ch == 'Y';

means only return true if y is pressed?
It literally means return a value indicating whether Y was pressed but the effect is that it returns a value indicating the user input, i.e. true for Y and false for N.
 
In many circles, it is recommended to write:
C#:
return ch == 'Y';

as opposed to:
C#:
return ch == 'Y' ? true : false;
or
C#:
bool isYes;
if (ch == 'Y')
    isYes = true;
else
    isYes = false;
return isYes;
or
C#:
if (ch == 'Y')
    return true;
else
    return false;
 
Back
Top Bottom