C# int.TryParse Method, Parsing Integers Correctly

You want to parse integers in your program written in the C# language, but some of the values may not be integers. There must not be any exceptions thrown during this parsing, as this could complicate your program's logic and make it slower. Here we look at the int.TryParse method, which provides an excellent and fast way of converting string inputs into ints, while avoiding exceptions and returning true and false depending on success.

Use int.TryParse to parse integers in most situations.        
... This is often faster and results in simpler logic.        
... This method is ideal for input that is not always correct.

Using int.TryParse

Here we see the int.TryParse method, which is considered a tester-doer. This method does not throw an exception when the input is invalid; instead, it handles errors by returning False. Your code that calls this method can simply check the return value. This is fastest when you need to deal with invalid input commonly.

=== Example program that uses int.TryParse (C#) ===

using System;

class Program
{
    static void Main()
    {
        //
        // See if we can parse the 'text' string. If we can't, TryParse
        // will return false. Note the "out" keyword in TryParse.
        //
        string text1 = "x";
        int num1;
        bool res = int.TryParse(text1, out num1);
        if (res == false)
        {
            // String is not a number.
        }

        //
        // Use int.TryParse on a valid numeric string.
        //
        string text2 = "10000";
        int num2;
        if (int.TryParse(text2, out num2))
        {
            // It was assigned.
        }

        //
        // Display both results.
        //
        Console.WriteLine(num1);
        Console.WriteLine(num2);
    }
}

=== Output of the program ===

0
10000

Description of the example. This example defines the Main entry point in a class Program. The int.TryParse method is called twice in the Main method. When you call the int.TryParse method, the first parameter must be a regular string type, and the second parameter is an OUT parameter, meaning it must be described with the word 'out'.

Using the out keyword. In the CLR, the out keyword is equivalent to the ref keyword on parameters. However, the out keyword helps with definite assignment analysis. This makes your programs more reliable because the compiler can help you make sure your variables are always in a valid state.

Invalid and valid string inputs. The program above uses int.TryParse on two input strings: the first input string is completely invalid, and uses the text "x". Obviously, that is not a numeric value. The second call uses the string "10000" which is parsed successfully by int.TryParse.

Using int keyword. Finally, it is useful to know that the word 'int' in the C# language simply aliases the System.Int32 type. Therefore, if you see code that uses "System.Int32.Parse" or "System.Int32.TryParse", it is equivalent to int.Parse and int.TryParse.

Definite assignment analysis

The C# compiler uses an interesting process called definite assignment analysis to prove that variables are in a valid state whenever they are used. This is a type of static analysis, and the algorithm is described in detail in the C# language specification. The 'out' keyword in int.TryParse tells the compiler that whenever int.TryParse returns, the second parameter will be assigned to a value.

See Out Parameter Example 1.

Testing for numeric strings

The int.TryParse method is also ideal for seeing if a string with any contents is a valid integer value. This means that if the string is "1" or "500", it will return true; if it is "x" or "cat", it will return false. This site has a detailed tutorial on testing strings for number values.

See String Number, Testing Numeric String Values.

Summary

Here we saw how you can use the int.TryParse method in your C# programs. This method is ideal for parsing strings into numbers, when the strings may not be valid or may contain erroneous characters. The method returns true if it succeeds, and false if it doesn't. Additionally, we reviewed the out keyword and definite assignment analysis, and explored some related issues.

See int.Parse for Integer Conversion.

See Format Articles.

© 2007-2010 Sam Allen. All rights reserved.

Dot Net Perls  Sam Allen