January 11, 2011

Converting/parsing string to int

Common C# application uses TextBoxes to enter some values which the program works with. So there is a need to convert some string from raw input to some other type. These examples show how to convert string to int.

Using static class Convert:
string input = "10";

int number;

number = Convert.ToInt32(input);

This method (and similar for other value types) can throw FormatException when input is not in the correct format (is not a number) of OverflowException if the string input is number but it's value is less than MinValue or greater than MaxValue.

The second option is to use Parse method:
result = int.Parse(input);

But this method can also throw some exceptions. Two of them are mentioned before: FormatException and OverflowException. Another exception, ArgumentNullException, is thrown when the argument (string input) is null.

The third option and in my opinion the best solution is to use TryParse method. This method doesn't throw exceptions so the isn't any exception handling slowing down the application. It only return true if the parse succeeded or false if it didn't.
bool parsed;
parsed = int.TryParse(input, out result);

I hope someone may find this snippet useful.