Is there a better way to validate user input in C# then using a do-while loop

22 hours ago 3
ARTICLE AD BOX

I like this approach in the do while loop. Not too sure about efficiency in terms of cpu cycles and performance. However, from a code efficiency point of view I think I would try and split out the validation to a separate method. This would also force you change where validation is set. Doing it inline rather than at the end.
Once I have one method doing the validation on just number and one method that is prompting the user and writing to the console. That would make it easier to throw some tests around the code.

You could also take me example and split out the string logic from the validation checking. If it is getting complicated or there is a reason for reuse you may want to look at creating an object to hold some of the validation out. In Python I might have just done this in a tuple.

int PlayerInput(string prompt, int min, int max) { do { Console.Write(prompt); string response = Console.ReadLine(); var consoleOutput = ValidatePlayerInput(response, min, max); if (string.IsNullOrEmpty(consoleOutput)) break; Console.WriteLine(consoleOutput); } while (true); //not ideal as this violates DRY int.TryParse(input, out number); return number; } string ValidatePlayerInput(string input, int min, int max) { bool isNumber = int.TryParse(input, out number); if (!isNumber) { return "Please enter a number"; } else if (number < min) { return $"Please enter a number from {min} to {max}"; } else if (number > max) { return $"Please enter a number from {min} to {max}"; } return null; }

If you intend to take your snippet, further be mindful of usages where the values entered are not 1 to 100 as your Console.WriteLine("Please enter a number from 1 to 100"); have been hard coded in your case. This could cause you some bugs in the future.

EDIT:
An option to make use of out variable.

int PlayerInput(string prompt, int min, int max) { int number; do { Console.Write(prompt); string response = Console.ReadLine(); var isValid = ValidatePlayerInput(response, min, max, out number, out string consoleOutput); if (isValid) break; Console.WriteLine(consoleOutput); } while (true); return number; } bool ValidatePlayerInput(string input, int min, int max, out int number, out string consoleOutput) { bool isNumber = int.TryParse(input, out number); if (!isNumber) { consoleOutput = "Please enter a number"; return false; } else if (number < min) { consoleOutput = $"Please enter a number from {min} to {max}"; return false; } else if (number > max) { consoleOutput = $"Please enter a number from {min} to {max}"; return false; } consoleOutput = null; return true; }
Read Entire Article