A common task in many applications is to convert a string value to a number. For example, if a user types a number into a TextBox, the Text property of the TextBox returns a string. But if you want to work with the value as a number, you need to convert it.
There are many ways to accomplish this task:
- Val(myString)
VB Only. This function returns the value of the first set of numbers in the string. If the string contains other characters, the evaluation stops at the first non-numeric character. So Val(“10 5th street”) returns 105. A run-time exception is generated if the value is too large or if the parameter cannot be converted to a string. - CType(myString, Integer)
VB Only. This function converts the expression to the specified data type. A run-time exception is generated if the conversion fails. - CInt(myString)
VB Only. This function converts the expression to an integer. It takes an object as a parameter. A run-time exception is generated if the conversion fails. - Convert.ToInt32(myString)
This function converts the expression to an integer. It provides overloads to convert from many different types of values to an integer. A run-time exception is generated if the conversion fails. - Integer.Parse(myString) / int.Parse(myString)
This function converts the expression to an integer. A run-time exception is generated if the conversion fails.
You may have noticed that each of these functions generate exceptions. In many cases, it would be nice to perform the conversion without generating an exception. This is especially important when processing user input because the user could leave the value blank or type in a value that is not numeric.
This is where TryParse comes in handy. It returns true or false defining whether the conversion was successful instead of generating an exception. The TryParse function was new in .NET 2.0.
In C#:
string value = "10";
int num;
if (int.TryParse(value, out num))
Debug.Print("Success! Value is {0}", num);
else
Debug.Print("Please enter a numeric value");
In VB:
Dim value As String = "10"
Dim num As Integer
If Integer.TryParse(value, num) Then
Debug.Print("Success! Value is {0}", num)
Else
Debug.Print("Please enter a numeric value")
End If
In both examples, the TryParse takes a string as the first parameter and an integer as an out (By Ref in VB) second parameter. If the conversion succeeds, the second parameter contains the converted value and TryParse returns true. If the conversion fails, the second parameter contains a value of 0 and TryParse returns false.
TryParse is also available for other data types such as Boolean, DateTime, Double, Decimal, and so on.
Enjoy!