This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 1.1+

Check if a String is Numeric with TryParse

When validating user input or information from integrated systems, it is often necessary to check if a provided string value is numeric. Testing both integer and floating point values is made simple is .NET 2.0 with the advent of the TryParse method.

Numeric Data

When working with user interfaces or with information that is being provided by third-party systems via direct integration or file transmission, it is not always possible to guarantee that the data being provided is suitable. In these situations validation is required. One of the more common validation tasks is ensuring that numeric information that is provided in a string can be converted to numeric information without causing an exception.

All of the basic .NET 2.0 numeric data types include a method named TryParse. This method attempts to convert the contents of a string to the appropriate numeric data type but unlike the Parse method no exception is thrown if the conversion is not possible. This means that the performance impact of catching exceptions is avoided. This method provides similar functionality to the "isnumeric" function included in other languages, with the added benefit of checking the string and returning its value in one step.

Using TryParse

The TryParse method is a static member of each numeric data type. The method accepts two parameters. The first parameter is the string containing the data that is to be converted. The second is an output parameter that holds the numeric value if the string is valid. The method returns a Boolean value that is true if the parsing is successful and false if it fails.

The following example demonstrates the use of TryParse for integer data.

string numeric = "12345";
string nonNumeric = "abcde";
int value;

if (int.TryParse(numeric, out value))
    Console.WriteLine("Value: {0}", value);
    Console.WriteLine("Conversion failed.");

if (int.TryParse(nonNumeric, out value))
    Console.WriteLine("Value: {0}", value);
    Console.WriteLine("Conversion failed.");


Value: 12345
Conversion Failed.


TryParse Limitation

The TryParse method has a size limitation. If the string contains a numeric value that is not within the range of values that the destination data type can hold, the parsing fails and the method returns false.

20 January 2008