Dela via


How to: Determine Whether a String Represents a Numeric Value (C# Programming Guide)

To determine whether a string is a valid representation of a specified numeric type, use the static TryParse method that is implemented by all primitive numeric types and also by types such as DateTime and IPAddress. The following example shows how to determine whether "108" is a valid int.

  int i = 0; 
  string s = "108";
  bool result = int.TryParse(s, out i); //i now = 108

If the string contains nonnumeric characters or the numeric value is too large or too small for the particular type you have specified, TryParse returns false and sets the out parameter to zero. Otherwise, it returns true and sets the out parameter to the numeric value of the string.

Note

A string may contain only numeric characters and still not be valid for the type whose TryParse method that you use. For example, "256" is not a valid value for byte but it is valid for int. "98.6" is not a valid value for int but it is a valid decimal.

Example

The following examples show how to use TryParse with string representations of long, byte, and decimal values.

// "1287543" represents a valid long, but "1287543.0" does not.
string numString = "1287543"; 
long number1 = 0;
bool canConvert = long.TryParse(numString, out number1);
if (canConvert)
    Console.WriteLine("number1 = {0}", number1);
else
    Console.WriteLine("numString is not a valid long");

byte number2 = 0;
// "255" represents a valid byte, but "256" does not.
numString = "255"; 
canConvert = byte.TryParse(numString, out number2);
if (canConvert)
    Console.WriteLine("number2 = {0}", number2);
else
    Console.WriteLine("numString is not a valid byte");

decimal number3 = 0;
// "27" also represents a valid decimal.
numString = "27.3"; 
canConvert = decimal.TryParse(numString, out number3);
if (canConvert)
    Console.WriteLine("number3 = {0}", number3);
else
    Console.WriteLine("numString is not a valid decimal");

// Output:
// number1 = 1287543
// number2 = 255
// number3 = 27.3

Robust Programming

Primitive numeric types also implement the Parse static method, which throws an exception if the string is not a valid number. TryParse is generally more efficient because it just returns false if the number is not valid.

Security

Always use the TryParse or Parse methods to validate user input from controls such as text boxes and combo boxes.

See Also

Tasks

How to: Convert a byte Array to an int (C# Programming Guide)

How to: Convert a string to an int (C# Programming Guide)

How to: Convert Between Hexadecimal Strings and Numeric Types (C# Programming Guide)

Concepts

Parsing Numeric Strings

Other Resources

Formatting Types