C# int.Parse for Integer Conversion

by Sam Allen - Updated January 8, 2010
Int keyword

You need to convert a string containing char digits into an integer, allowing you to use a numeric value. There are several methods, such as int.Parse, that are ideal for this. Here we look at three useful methods that are effective, assuming your code must only accept very simple input strings, using code in the C# programming language.

String input:  "500"
               "-5" 
               "xyz"
               "0.5"
Parsed number: 500
               -5
               Error
               Error

Using int.Parse

First, here we see the int.Parse method. int.Parse is the simplest method, and is also the author's favorite for many situations. It throws exceptions on invalid input, which can be slow if they are common. It is does not contain any internal null checks.

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

using System;

class Program
{
    static void Main()
    {
        // Convert string to number.
        string text = "500";
        int num = int.Parse(text);
        Console.WriteLine(num);
    }
}

=== Output of the program ===

500

What MSDN says: "All numeric types have a static Parse method that you can use to convert a string representation of a numeric type into an actual numeric type." [Parsing Numeric Strings - MSDN]

What is int.TryParse?

One of the most useful methods for parsing integers in the C# language is the int.TryParse method. This method works the same way as int.Parse as shown above, but it uses somewhat more confusing syntax and does not throw exceptions. You must describe the second parameter with the out modifier, and TryParse also returns true or false based on its success. This method is described in more detailed on another page.

(See int.TryParse Method, Parsing Integers Correctly.)

Using Convert.ToInt32

Third, we look at the Convert.ToInt32 method. Convert.ToInt32, along with its siblings Convert.ToInt16 and Convert.ToInt64, is actually a static wrapper method for the int.Parse method. It can be slower than int.Parse if the surrounding code is equivalent.

=== Example program that uses Convert.ToInt32 (C#) ===

using System;

class Program
{
    static void Main()
    {
        // Convert 'text' string to an integer with Convert.ToInt32.
        string text = "500";
        int num = Convert.ToInt32(text);
        Console.WriteLine(num);
    }
}

=== Output of the program ===

500

Its syntax is more confusing. The syntax for this method may be more confusing as it uses the bit size of the int, which may not be really important for some of your code. The framework can better deal with that sort of detail.

It is slower and more complicated. These Convert methods don't seem to add any value here, and may be harder to read for some. It is probably better to focus more on the faster and simpler functions.

Which method should I use?

The author's recommendation is to use int.Parse when your input will be valid, as it makes for simpler calling code. It isn't always perfect, but it is a winner. On the other hand, use int.TryParse when you will be dealing with corrupt data.

(See Unsafe Int Parse.)

(See double.Parse Method.)

Input contains non-numeric or invalid characters
Use int.TryParse. [See link in "What is int.TryParse?"]

Input is valid and all numeric
Use int.Parse.

Input is guaranteed to be valid
(Must be parsed really quickly)
Use unsafe code if performance is critical.

Input has many digits or decimal places
Use double.Parse or double.TryParse.

Testing for numeric content

You can see a more detailed and complete example of testing strings to see if they are numbers in another article on this site. The technique involves using int.TryParse or similar methods in a static Boolean method. This is useful for validating input on the server or in TextBox controls.

(See String Number, Testing Numeric String Values.)

Summary

Here we saw how you can parse integers in the C# language very easily with three different methods. Before frameworks were widely used, programmers would write their own integer conversion routines, but this quickly became very complex. The .NET framework provides much more built-in functionality.

(Do not copy this page.)

Dot Net Perls | Search
Numbers | Absolute Value and Math.Abs Method | Convert Bool to Int | int.Max and Min Constants | int.TryParse Method, Parsing Integers Correctly | Random Number Generator
C# | Parameter Optimization Tip | SaveFileDialog Tutorial | IntegralHeight Property (Windows Forms) | Array.FindIndex Method
© 2010 Sam Allen. All rights reserved.
Dot Net Perls | Sam Allen