Visual C# 2005 Guide
Validating User Input

There are many things that can make your programs crash. This is different from the compiler errors you get when you have made a mistake in the code you write. Some of our programs rely on the user inputting the correct type of data. For example, when our programs expect an integer to be input, they crash if a string or if nothing is entered.

A well-designed program caters for this situation. One approach is to validate the input, inform the user if they have made an error and give them another chance. This usually means some sort of loop within the program logic.

Checking That Something Is Entered

The following program repeats a request for string data to be entered until something is typed at the prompt.

Console.Write("Enter your name: ");
string name = Console.ReadLine();
while (name == "")
{
   Console.Write("You need to enter your name: ");
   name = Console.ReadLine();
}
Console.WriteLine("Thanks for entering your name, {0}", name);
Console.ReadLine();

The same logic could be applied to a numeric value. Bear in mind that all information entered at the console comes as a string initially and you will need to perform conversions.

Having A Go

  1. Write a program that performs division only when two integers are entered, the second is smaller than the first, the second number is not a zero and both numbers are less than 100.
  2. Write a program that holds the user in a continual loop until they enter a specific word.