Hi I have only recently started using c# in my first year of university. I have done a little vb before but pretty much a noob.
I have to write a simple console application that counts how many coins are required to make up a particular number given by the user.

My question is how do I check that the input giving by the user is a valid integer before I convert the string (Num) to an Integer (i).

This is what I have:

while (Num = "")
{
Console.WriteLine("Please enter a value");
Num = Console.ReadLine();
}

If (Num !="")

i = Convert.ToInt32(Num);

Any help would be greatly appreciated also any constructive criticism is welcome.

Edited 6 Years Ago by __avd: Added [code] tags. Encase your code in: [code] and [/code] tags.

1) Don't assume the input should be an integer. If you want to calculate the number of coins required, you should allow for dollars and cents. Use a double or decimal data type instead.

2) For validation, use the .TryParse(string input, out result) method. The method itself returns a bool, the out parameter (result) is what would contain the parsed value. You would use it like this:

string input = "10.75"; // change to user input!
double output = 0d;

bool validInput = double.TryParse(input, out output); 
// other TryParse methods:
//    int.TryParse
//    long.TryParse
//    short.TryParse
//    float.TryParse
//    decimal.TryParse
//    char.TryParse
//    DateTime.TryParse
//    could be more!

if (validInput)
{
   // ok to work with output value
}
else 
{
   // not ok to work with output  value, consider prompting user for another value
}

The reason you want to use TryParse is that it gives you a boolean return value indicating success or failure. Other methods such as Convert.To[Type] or [Type].Parse will throw exceptions on invalid inputs. You can catch these and handle them the same way you would a false condition of TryParse, but it is inefficient to do so.

Spot on, almost word for word what i was about to say. Although your sample code is probably better commented than mine would have been ;)

Thank you very much this is very helpful, just what I was looking for. :)

This question has already been answered. Start a new discussion instead.