Skip to main content

How to Convert a String to an int with int.Parse in C#

· 6 min read
Jagdish Kumawat
Founder @ Dewiride

int.Parse("42", CultureInfo.InvariantCulture) turns the text "42" into the number 42, which you can add, compare and count with. Text that isn't a whole number makes it throw a FormatException.

Microsoft's reference: Converts the string representation of a number to its 32-bit signed integer equivalent. A 32-bit signed integer is an int.

Numbers often arrive as text: typed into a form, read from a file or sent by another program. The text "12" is two characters, not a number you can add, until you convert it.

Syntax​

Syntax
int <number> = int.Parse(<text>, CultureInfo.InvariantCulture);
int <number> = int.Parse(<text>);
PartWhat it is
<text>The string to convert, such as "42"
CultureInfo.InvariantCultureThe culture whose rules read the text, such as which sign means minus. It needs using System.Globalization;
<number>The int you get back

The second form uses the computer's own culture. The reference: The s parameter is parsed using the formatting information in a NumberFormatInfo object initialized for the current system culture. And which text works: In addition to decimal digits, only leading and trailing spaces together with a leading sign are allowed.

The Example​

A console app called IntParse joins two numbers that arrive as text, adds them after converting them with int.Parse, converts text with spaces and a minus sign, and catches the FormatException for "abc".

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n IntParse
cd IntParse
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/IntParse/IntParse.csproj:
Determining projects to restore...
Restored /Users/you/source/IntParse/IntParse.csproj (in 170 ms).
Restore succeeded.

dotnet new console -n IntParse creates a folder named IntParse with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or IntParse.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First the text and the numbers:

Program.cs (text and numbers)
using System.Globalization;

// Two numbers that arrive as text, such as from a file.
string first = "12";
string second = "30";
Console.WriteLine($"Joined as text: {first + second}");

// int.Parse turns each text into an int.
int a = int.Parse(first, CultureInfo.InvariantCulture);
int b = int.Parse(second, CultureInfo.InvariantCulture);
Console.WriteLine($"Added as numbers: {a + b}");
  • first + second joins two strings into one.
  • int.Parse(first, CultureInfo.InvariantCulture) converts "12" into the int 12. With two int values, a + b adds them.

Then spaces and a sign:

Program.cs (spaces and a sign)
// Spaces around the number and a sign in front are allowed.
int c = int.Parse(" -7 ", CultureInfo.InvariantCulture);
Console.WriteLine($"With spaces and a sign: {c.ToString(CultureInfo.InvariantCulture)}");

c.ToString(CultureInfo.InvariantCulture) writes the result back out with a plain minus sign. Writing a number follows a culture too: in a check, -7 written for Swedish started with U+2212, a different minus sign, and for Egyptian Arabic with an invisible mark, U+061C, before the minus.

Then the error:

Program.cs (text that isn't a number)
// Text that isn't a whole number throws a FormatException.
try
{
int d = int.Parse("abc", CultureInfo.InvariantCulture);
Console.WriteLine(d);
}
catch (FormatException ex)
{
Console.WriteLine($"FormatException: {ex.Message}");
}

try runs the conversion, and catch (FormatException ex) catches the error and prints its message.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
Joined as text: 1230
Added as numbers: 42
With spaces and a sign: -7
FormatException: The input string 'abc' was not in a correct format.

macOS-style terminal window titled Terminal — IntParse showing dotnet run printing Joined as text: 1230, Added as numbers: 42, With spaces and a sign: -7 and FormatException: The input string 'abc' was not in a correct format.

  • As text, "12" and "30" joined into 1230. As numbers, they added up to 42.
  • " -7 " became -7: the spaces were skipped and the minus sign kept.
  • "abc" threw a FormatException with the message The input string 'abc' was not in a correct format. The reference lists this exception for when s is not of the correct format.

The Complete File​

macOS-style code window titled Program.cs — IntParse showing two numbers as text joined, then converted with int.Parse and the invariant culture and added, text with spaces and a minus sign converted to -7, and a try and catch block that catches the FormatException for abc

Program.cs
using System.Globalization;

// Two numbers that arrive as text, such as from a file.
string first = "12";
string second = "30";
Console.WriteLine($"Joined as text: {first + second}");

// int.Parse turns each text into an int.
int a = int.Parse(first, CultureInfo.InvariantCulture);
int b = int.Parse(second, CultureInfo.InvariantCulture);
Console.WriteLine($"Added as numbers: {a + b}");

// Spaces around the number and a sign in front are allowed.
int c = int.Parse(" -7 ", CultureInfo.InvariantCulture);
Console.WriteLine($"With spaces and a sign: {c.ToString(CultureInfo.InvariantCulture)}");

// Text that isn't a whole number throws a FormatException.
try
{
int d = int.Parse("abc", CultureInfo.InvariantCulture);
Console.WriteLine(d);
}
catch (FormatException ex)
{
Console.WriteLine($"FormatException: {ex.Message}");
}

Common Mistakes​

MistakeWhat happensDo this instead
Converting text with a decimal point, such as "12.5"System.FormatException: The input string '12.5' was not in a correct format. An int has no decimalsUse decimal.Parse or double.Parse: decimal.Parse("12.5", CultureInfo.InvariantCulture) gave 12.5
Converting a number bigger than an int can hold, such as "3000000000"System.OverflowException: Value was either too large or too small for an Int32.Use long.Parse, which gave 3000000000
Leaving out the cultureThe computer's culture decides. With the current culture set to Egyptian Arabic, ar-EG, int.Parse("-15") threw a FormatException: The input string '-15' was not in a correct format. That culture's minus sign is U+061C followed by a hyphenPass CultureInfo.InvariantCulture, which gave -15

FAQ​

What does int.Parse do with empty text or null?​

It throws. Empty text gave FormatException: The input string '' was not in a correct format., and null gave ArgumentNullException: Value cannot be null. (Parameter 's').

When should I use int.TryParse instead?​

When bad text is expected, such as what people type. The reference: The TryParse method is like the Parse method, except the TryParse method does not throw an exception if the conversion fails. int.TryParse("abc", CultureInfo.InvariantCulture, out int number) returned False, and number was 0. Use int.Parse when the text should always be a whole number, and a bad one is an error.

Conclusion​

int.Parse(text, CultureInfo.InvariantCulture) turns text such as "42" or " -7 " into an int, and throws a FormatException for text that isn't a whole number. Pass the culture so the result doesn't depend on the computer, and catch the exception, or use int.TryParse, where the text can be wrong.

Additional Resources​