When to use Parse, Convert, and TryParse in C#

When converting values in C#, we are given three options : Parse, Convert, and TryParse. My suggestion would be to use which method based on where the conversion is taking place. If you are validating user input, an int parse or a convert will allow you to give specific error messages. If you are merely converting in a more discreet function, then maybe a TryParse is what you need.

Examples

Int.Parse

A simple int.Parse with some common exceptions to check for.

            try
            {
                int.Parse(value);
            }
            catch (FormatException)
            {
                //If we can't parse the string
            }
            catch (ArgumentNullException)
            {
                //If the string is null
            }
            catch(StackOverflowException)
            {
                //If the string is outside the possible integer values
            }

Convert

Convert almost seems like an after thought of a parse. Convert will handle a null and the conversion automatically unless you enter a non-numeric (FormatException) or If the string is outside the possible integer values(StackOverflowException).

            try
            {
                Convert.ToInt32(value);
            }
            catch(FormatException)
            {
                //If we can't parse the string
            }
            catch (OverflowException)
            {
                //If the string is outside the possible integer values
            }

int.TryParse

Now let’s state the obvious. TryParse is very similar to parse, the main difference is TryParse was created to reduce the need for exception handling when parsing fails on a variable. So hypothetically, if you are pretty sure 95% of the time you conversion will succeed, use Parse with some exception handling. However, most developers will tell you now days to use try parse everywhere you can to minimize the use of exception handling as much as possible.

            int number;
            bool result = int.TryParse(value, out number);

            if (result)
            {
                //We now have our converted integer.
            }
            else
            {
                //Something went wrong with the conversion. Our number variable will be equal to zero.
            }

Jacob Saylor

Software developer in Kentucky

1 Response

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: