C# int.Parse

Int keyword

The int.Parse method converts strings into ints. Often we have strings containing char digits. After converting them into integers, we can use numeric values.
There are several C# methods,
including int.Parse,
that are ideal for this.

Int
String input:

"500"
"-5"
"xyz"
"0.5"

Parsed number:

500
-5
Error
Error 2

Example

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

Null
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

500

TryParse

Try keyword

A useful method 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.

int.TryParse

Tip:You must describe the second parameter with the out modifier. TryParse also returns true or false based on its success.

OutTrue, False

Convert.ToInt32

Convert or change

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.

Static Method
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

500

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 .NET Framework can better deal with that sort of detail.

So:These Convert methods don't seem to add any value here. They also may be harder to read for some developers.

Discussion

Squares

My recommendation is to use int.Parse when your input will be valid, as it leads to 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.

Tip:If your input contains non-numeric or invalid characters, use int.TryParse.

Tip 2:If your input is valid and all numeric, and performance is not extremely critical, use int.Parse.

Tip 3:If your input is guaranteed to be valid, use custom code if performance is critical. Otherwise, use int.Parse.

int.Parse Optimization

Tip 4:If your input has many digits or decimal places use double.Parse or double.TryParse.

Summary

Framework: NET

We parsed integers with three different methods. Before frameworks were widely used, programmers would write their own integer conversion routines. This quickly became very complex. The .NET Framework offers built-in functionality.


C#: String