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. With int.Parse, TryParse and Convert.ToInt32 we apply conversions.

Int
String input:

"500"
"-5"
"carrot"
"0.5"

Parsed number:

500
-5
Error
Error

Example

C# language

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

FormatException

Error

The int.Parse method does not tolerate any nonsense. With an invalid string, it will throw a FormatException. We can catch this using a try-catch construct, but using the int.TryParse method is usually better.

Program that encounters FormatException: C#

using System;

class Program
{
    static void Main()
    {
	string input = "carrot";
	// ... This will throw an exception.
	int carrots = int.Parse(input);
	Console.WriteLine(carrots);
    }
}

Output

Unhandled Exception: System.FormatException:
Input string was not in a correct format.
   at System.Number.StringToNumber(String str, NumberStyles options, ...
   at System.Number.ParseInt32(String s, NumberStyles style, ...

TryParse

Try keyword

A useful method for parsing integers 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

Confusing:The syntax here may be more confusing. It uses the bit size of the int, which may not be relevant to the code's intent.

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

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

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

Before frameworks were widely used, programmers would write their own integer conversion routines. This was complicated and redundant. With these three methods, the .NET Framework has built-in functionality.


C#: String