How to Convert a string to an int in C#

By FoxLearn 2/4/2025 6:28:08 AM   104
When working with C#, you'll often need to convert a string into an integer.

Luckily, C# provides several methods to perform this conversion, each with its own behavior and use cases. The three most commonly used methods are:

Using int.Parse()

The int.Parse() method takes a string as input and converts it to a 32-bit integer. If the string is not a valid integer, it throws an exception.

Here’s an example of using int.Parse():

string input = "123";
int number = int.Parse(input);

In this case, the string "123" is successfully converted to the integer 123.

Handling Conversion Failures

int.Parse() can throw exceptions when the string cannot be converted. Here are some scenarios where it might fail:

Format Exception - When the string isn't a valid number:

int.Parse("abc");  // System.FormatException: Input string was not in a correct format.

Overflow Exception – When the value is too large or small for an Int32:

int.Parse("999999999999999999999999999999999999999");  // System.OverflowException: Value was too large for an Int32.

ArgumentNullException – When the string is null:

int.Parse(null);  // System.ArgumentNullException: Value cannot be null.

You can catch these exceptions if you need to handle them specifically. Otherwise, for scenarios where you just need to check if the conversion succeeded, consider using int.TryParse() instead.

Using int.TryParse()

The int.TryParse() method is more flexible than int.Parse() because it does not throw an exception when conversion fails. Instead, it returns false if the conversion is unsuccessful. If the conversion succeeds, it returns true and provides the parsed integer via an out parameter.

Here’s an example of how to use int.TryParse():

string input = "123";

if (int.TryParse(input, out int number))
{
    // Use number
    Console.WriteLine($"Input + 1: {number + 1}");
}
else
{
    Console.WriteLine($"Couldn't convert {input} to an int");
}

In this example, the string "123" is successfully converted, and the output will be:

Input + 1: 124

What Happens When Conversion Fails?

If int.TryParse() fails, the out parameter is set to 0, which is the default value for integers. Here’s an example of a failed conversion:

int.TryParse("abc", out int number);
Console.WriteLine(number);  // Output: 0

In this case, the string "abc" cannot be converted to an integer, so the output is 0. In most cases, you won’t want to use the int if the conversion failed.

Using Convert.ToInt32()

The Convert.ToInt32() method is another way to convert a string to an integer. It behaves differently from int.Parse() and int.TryParse(), with three possible outcomes:

  • If the string is null, it returns 0.
  • If the string is valid, it converts the string to an integer.
  • If the string is invalid, it throws an exception.

Here are some examples:

// Valid string
int number = Convert.ToInt32("123");

// Null string
int number2 = Convert.ToInt32(null);
Console.WriteLine(number2);  // Output: 0

// Invalid string
Convert.ToInt32("a");  // Throws System.FormatException: Input string was not in a correct format.

Unlike int.Parse(), Convert.ToInt32() will return 0 if the string is null. But, like int.Parse(), it will throw an exception if the string cannot be parsed into a valid integer.

Converting Formatted Strings

Sometimes, the string you want to convert may contain special formatting, such as currency symbols or commas. In such cases, you can use the NumberStyles parameter in methods like int.Parse() or int.TryParse() to handle these formats properly.

Here’s an example where we convert a formatted string using int.Parse():

using System.Globalization;

int negativeOneK = int.Parse(" -$1,000 ", NumberStyles.Currency);

Console.WriteLine($"Parsed int: {negativeOneK}");  // Output: Parsed int: -1000

In this case, the string " -$1,000 " contains a currency symbol, and NumberStyles.Currency tells the parser to recognize and handle it correctly.

By default, int.Parse() and int.TryParse() use the current culture’s formatting settings (i.e., CultureInfo.CurrentCulture).

In C#, you have several options when converting a string to an integer:

  • int.Parse() is straightforward but throws exceptions if the conversion fails.
  • int.TryParse() is safer because it doesn’t throw exceptions and returns false when the conversion fails.
  • Convert.ToInt32() can handle null values and behaves similarly to int.Parse() but with a default behavior of returning 0 for null.

Each method has its use case, and choosing the right one depends on your requirements for handling invalid input and exceptions. By understanding these different approaches, you can confidently convert strings to integers in C#.