Saturday, July 3, 2010

Casting using TryParse, Convert , int.Parse()

using System.Convert, ToInt32() for example allow you to convert 19 different type to int.
in other hand using int.Parse(), accept string parameters only, and it's useful to be used with Console.readLine, but what if the user enter a textual data for example, "Ahmed" or "123Ali"
here tryParse would solve the issue.
in this example:
I created 2 variables (input) is the value I need to parse and (num) as an int to hold the integral parsed new value.

int num;
if (int.TryParse(input , out num))
{
if (num> 10)
Console.WriteLine(num.ToString() + ">10");
}
else
{
Console.WriteLine(num);
}

No comments:

Post a Comment