Monthly Archives: December 2009

Taking Control of Your Int Parsing

We’ve all converted strings to integers using the handy Parse and TryParse methods of the Int structure. Both methods have an overload, which takes a nice little enumeration called NumberStyles, that gives you some finer grain control of how you parse those strings.

An example will shine a light on what I am going on about. Firstly, imagine you have a string which contains spaces and a negative integer. You want to make sure that your integer gets parsed properly. You could write the following code:

        // Parse the string, allowing a leading sign, and ignoring leading and trailing white spaces.
        string num = "    -22   ";
        int val;
        bool result = int.TryParse(num, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, null, out val);

        // val will have a value of -22

Another example is where you may want to parse a string, containing a number in brackets, to a negative integer value. That can be achieved using the NumberStyles.AllowParentheses enumeration value:

num = "(37)";
val = int.Parse(num, NumberStyles.AllowParentheses);

// val will have a value of -37

There’s a whole raft of other values for this enumeration, which gives you considerable flexibility in controlling how you parse strings into integers. You’ll find them in the System.Globalization namespace. Have a play, next time you’re bored!