I want to create a piece of code that sets a boolean variable to true if the user responds through Console.ReadLine. This variable comes to use later in some other code. The only code I've tried so far is:
bool hastyped = false;
var input = Console.ReadLine();
hastyped = true;
How can I make this work?
For reference the actual code that I'm using goes something more like:
response = Console.ReadLine();
hastyped = true;
That is, after initialising the variables of course.
To see if the User actually inputted something you can check the string you save the Input into.
Because when you hit the Enter Key, Console.ReadLine
is an empty string. So you can check with .IsNullOrEmpty()
to see if the Input actually contains any characters.
Or you could even use .IsNullOrWhiteSpace()
, to check if the Input contains only Whitespaces as well.
Example:
// Getting Input from Console
string input = Console.ReadLine();
// Check if Input contains more than whitespaces and isn't empty or null,
// if it doesn't bool is true else it's false
bool hastyped = !string.IsNullOrWhiteSpace(input);