MorkaLork Development

Interesting stuff I've picked up over the years...

TryParse

2009-02-18 08:22:00 | 392 views |

The Basics




From MSDN

Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded.



public static bool TryParse(string s, out int result)



Getting into it


Allright. TryParse is an excelent way to parse data without using Try..Catch. TryParse returns a boolean value instead of the number directly. If successfull, the method will also output the value requested.

Example:


Console.Write("Enter an integer value: ");
string myNumber = Console.ReadLine();
int myInt;
bool myCheck;

myCheck = int.TryParse(myNumber, out myInt);

if(myCheck == false)
{
Console.WriteLine("Error: {0} is not an integer value", myNumber);
}
else
{
Console.WriteLine("Congratulations, {0} is an integer value!", myInt);
}
Console.Read();


As we can see assign the boolean variabel myCheck the return of the int.TryParse method. The return will be either true or false depending on the outcome. If the result is true, our TryParse will also output the converted value into our integer variable myInt so that we can use it later.

The alternative



If we don't want to use TryParse we can use normal parsing, but then we'd have to use a try...catch statement, like this:



Console.Write("Enter an integer value: ");
string myNumber = Console.ReadLine();
int myInt;
bool myCheck;

try
{
myInt = int.Parse(myNumber);
}
catch (FormatException ex1)
{
Console.WriteLine("Error: {0}", ex1);
myInt = 0;
}
catch (OverflowException ex2)
{
Console.WriteLine("Error: {0}", ex2);
myInt = 0;
}
Console.WriteLine("Converted string: {0}", myInt);

Console.Read();


Try...Catch is a good thing, but it's just not always needed, like in this case.

Good luck using TryParse!


Article comments

Feel free to comment this article using a facebook profile.

I'm using facebook accounts for identification since even akismet couldn't handle all the spam I receive every day.