#1,011 – TryParse Indicates Whether a Parse Operation Will Succeed

You can use the Parse method to convert a string that represents a number to its equivalent numerical representation.

            string numberString = "108";
            int number = int.Parse(numberString);

If the string does not represent a value of the associated numeric type, or represents a numeric value that is outside the range of the type, a FormatException or OverflowException is generated.

            int n1 = int.Parse("3.4");    // FormatException

You can avoid the exception by using the TryParse method.  If the parse operation succeeds, the parsed value is stored in the output parameter and TryParse returns true.  If the parse operation does not succeed, the output parameter is not written to and TryParse returns false.  No exception is thrown.

            int n1;
            if (int.TryParse("3.4", out n1))
                Console.WriteLine("Parse worked--n1 contains number");
            else
                Console.WriteLine("Can't parse");

1011-001

Advertisements