There are two way of converting strings to numerical values in .NET. The first one, supported since the first version of the platform, is the use of System.Convert class. It has methods like ToInt32, ToChar, ToDouble, ToDataTime, ToDecimal, etc.

Here is an example of converting string “123″ to numerical value 123.

string text = "123";
int number = Convert.ToInt32(text);
Console.WriteLine(number);

The catch with this method (and all the others from Convert) is that an exception is thrown, if the conversion failed.

 Unhandled Exception: System.FormatException: Input string was not in a correct f
 ormat.
    at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer&
        number, NumberFormatInfo info, Boolean parseDecimal)
    at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
    at System.Convert.ToInt32(String value)
    at vs2008_cs_test.Program.Main(String[] args) in [...]\Program.cs:line 14

The correct use of ToIn32 is:

string text = "123s";
try
{
    int number = Convert.ToInt32(text);
    Console.WriteLine(number);
}
catch(FormatException e1)
{
    Console.WriteLine(e1.Message);
}
catch(OverflowException e2)
{
    Console.WriteLine(e2.Message);
}

Probably because too many programmers failed to try-catch these ToXXX methods and run into trouble, beginning with version 2.0 of the framework, a second method of converting string to numerical values was provided. All built-in numerical types (such as char, boolean, int, double, decimal, etc.) and others (such as DateTime, TimeSpan, IPAddress, etc.) have a static method called TryParse, that takes an in parameter the string to convert and and out parameter, the parsed value, and returns a boolean value to indicate success or failure.

string text = "123";
int number;
if(int.TryParse(text, out number))
{
    Console.WriteLine(number);
}
else
{
    Console.WriteLine("Could not parse string!");
}

Between the two, the second is recommended because is less error-prone. If an error occurs during parsing, you don’t get an exception so your program won’t crash. Moreover, the out value is set to the default value (false, 0, etc.).

Hits for this post: 11105 .