Convert .NET data types using Parse and TryParse

Waqas Anwar
01 April 2008
19425 Views

All base types in .NET Framework offer Parse method which is used to convert string value to different types. For example, you can convert string into int, double, short, float, boolean etc. Parse methods are very useful because programmers don’t need to write any of their own conversion routines for common input scenarios. However, these methods also have some problems which programmers must need to keep in mind when they are writing their code which is using Parse methods

First see below some simple examples of Parse method.

C#
string input = "5";
           
int i = Int32.Parse(input);
double d = Double.Parse(input);
char c = Char.Parse(input);
bool b = Boolean.Parse(input);

VB.NET
Dim input As String = "5"

Dim i As Integer = Int32.Parse(input)
Dim d As Double = Double.Parse(input)
Dim c As Char = Char.Parse(input)
Dim b As Boolean = Boolean.Parse(input)

The above code looks very simple as I am trying to convert string input to different .NET types such as int, double etc. If you have this code in .NET application and input string is coming from the user than there are chances that you have bad data for parsing and this will cause your program to fail and .NET Runtime will throw Exception.

Here are two common causes of Exceptions in Parse method.


   1.    If input is "hello" Parse method throws FormatException 
   2.    If input is null Parse method throws ArgumentNullException

Although, programmers can boost application performance by checking null before conversion and handling conversion errors using exception handling (try-catch) blocks such as the code below demonstrates, but exceptions are expensive to handle as far as computations are concerned and programmers should avoid them for normal program flow.


C#
string input = "5";
           
int i = 0;
double d = 0.0;

if (input != null)
{
    try
    {
        i = Int32.Parse(input);
        d = Double.Parse(input);
    }
    catch (FormatException ex)
    {
        i = 0;
        d = 0.0;
    }
}


VB.NET
Dim input As String = "5"
Dim i As Integer = 0
Dim d As Double = 0

If input IsNot Nothing Then
    Try
        i = Int32.Parse(input)
        d = Double.Parse(input)
    Catch ex As FormatException
        i = 0
        d = 0
    End Try
End If


If user input conversion is very common in your .NET application you should use conditions rather than exceptions. Before .NET there was no easy way to avoid exception handling code to handler conversion errors but .NET Framework 2.0 added new method “TryParse” to all relevant base types to solve this problem. Like Parse, TryParse also converts a string value into different types but unlike Parse, TryParse returns a Boolean (true or false) to indicate whether conversion is failed or not.

Following code will show you how you can use TryParse in both C# and VB.NET


C#
string input = "5";
           
int i = 0;
double d = 0.0;

bool result1 = false, result2 = false;

if (input != null)
{
    result1 = Int32.TryParse(input, out i);
    result2 = Double.TryParse(input, out d);
}

Console.WriteLine("Result 1: " + result1);
Console.WriteLine("Result 2: " + result2);

Console.WriteLine(i);
Console.WriteLine(d);


VB.NET
Dim input As String = "5"

Dim i As Integer = 0
Dim d As Double = 0

Dim result1 As Boolean = False, result2 As Boolean = False

If input IsNot Nothing Then
    result1 = Int32.TryParse(input, i)
    result2 = Double.TryParse(input, d)
End If

Console.WriteLine("Result 1: " + result1)
Console.WriteLine("Result 2: " + result2)

Console.WriteLine(i)
Console.WriteLine(d)


Remember there is no difference in speed if string you are parsing is parsed successfully by using both Parse and TryParse, however if there is a parsing error than TryParse is much faster than Parse. I hope you will also start using TryParse instead of Parse in your .NET application to increase performance.