Convert string to int in C#

In C#, there are several methods available for converting strings to other data types. Following are some of the most common string conversion methods:

int.Parse() method

The simplest way to convert a string to an integer in C# is by using the int.Parse method:

string numberString = "42"; int number = int.Parse(numberString); Console.WriteLine("The number is: " +number); //Output:The number is: 42

FormatException

If the string can not be parsed to an integer, int.Parse will throw a FormatException. To handle this, you can use the int.TryParse method, which returns a bool indicating whether the parsing was successful:

string numberString = "42"; if (int.TryParse(numberString, out int number)) { Console.WriteLine("The number is: " + number); } else { Console.WriteLine("can't parse !!"); } //Output:The number is: 42

Different types of Parse methods


string to int in C#

In C#, there are several Parse methods for different data types. The following are some of the most commonly used Parse methods:


Parse methods Description
int.Parse Converts a string representation of a number to an int.
float.Parse Converts a string representation of a number to a float.
double.Parse Converts a string representation of a number to a double.
decimal.Parse Converts a string representation of a number to a decimal.
bool.Parse Converts a string representation of a boolean value to a bool.
DateTime.Parse Converts a string representation of a date & time to a DateTime.
Guid.Parse Converts a string representation of a globally unique identifier to a Guid value.

Using int.TryParse

The int.TryParse method in C# allows you to attempt to convert a string representation of a number to an integer. If the string can be successfully parsed, the method returns true and the result is stored in the output parameter. If the string can not be parsed, the method returns false and the output parameter is not modified:

string input = "42"; if (int.TryParse(input, out int result)) { Console.WriteLine("The number is: " + result); } else { Console.WriteLine("can't parse !!"); } //Output:The number is: 42

Using Convert class

In C#, you can use the Convert class to convert a string to an integer. The Convert class provides the ToInt32 method, which can be used for this purpose:

string input = "42"; int result = Convert.ToInt32(input); Console.WriteLine("The number is: " + result); //Output:The number is: 42

Like the int.Parse method, Convert.ToInt32 can throw a FormatException if the string can not be converted to an integer. To handle this, you can wrap the call in a try-catch block:

string input = "42"; try { int result = Convert.ToInt32(input); Console.WriteLine("The number is: " + result); } catch (FormatException) { Console.WriteLine("The string could not be converted to an integer."); } //Output:The number is: 42


NEXT.....String and System.string