I'm making a simple guessing game in C# where the computer generate a number between 1-10, and I got both a clickEvent and a KeyPressedEvent (to the Enter key) to "submit" the guess.
I'm trying to make it so you can just type "reset" into the text field and hit enter to call on the StartNewGame() method but it doesn't seem to activate the method.
I tried both
if (userReset.Equals("reset"))
{
StartNewGame();
}
and
if (userReset == "reset" )
{
StartNewGame();
}
but it does not seem to call on that StartNewGame()
I'm using Visual Studio 2019 on Windows 10.
The problem with the code is that the variable userReset
is set to an empty string, and nothing else:
String userReset = "";
Therefore, when you are comparing it to the text "reset"
the result is false
.
Instead you should perhaps implement it like this:
...
string userReset = txtGuess.Text
...
if (userReset.Equals("reset"))
...
Or alternatively, don't use a variable at all:
...
if (txtGuess.Text == "reset")
...
Incidentally, I would personally use this in the else
from the int.TryParse
:
if (int.TryParse(txtGuess.Text, out guess))
{
...
}
else if (txtGuess.Text == "reset")
{
...
}
This is because if the text is a number then it will never be "reset"
(and vice versa) which saves checking the value of the TextBox
unnecessarily.
As pointed out by @TimSchmelter in the comments, it may also make sense to ignore the case of the text being entered (i.e. make the comparison case-insensitive) so that the user could type reset
, Reset
, ReSeT
, etc.
To achieve this, use a case-insensitive comparison:
else if (txtGuess.Text.Equals("reset", StringComparison.OrdinalIgnoreCase))