I have public string method with an if/else statement. When I don't put a return keyword on the else, I get the error that not all code paths return a value but when I add the return to the else statement, I get an Use of unassigned local variable 'result'. When I do return "Please enter a valid number";, nothing displays on the console when I type in any letter. I need to let the user know that they entered something in that couldn't be converted into an integer.
public string AddNumbers(string userInputString)
{
int result;
int num2 = RandomNumberInt();
bool isTrue = int.TryParse(userInputString, out int num1);
if (isTrue == true)
{
result = num1 + num2;
Console.WriteLine("Adding your number and a random number, please wait...");
Thread.Sleep(1000);
Console.WriteLine("{0} + {1} = {2}", num1, num2, result);
isTrue = true;
return result.ToString();
}
else
{
return "Please enter a valid number";
}
}
Aucun commentaire:
Enregistrer un commentaire