To convert a string to an integer in C#, use int.TryParse when the text may be invalid, or int.Parse when you expect valid numeric text. For example, converting "83" gives the integer 83, which you can use in calculations.
This tutorial covers C# and .NET. The examples use the C# string type and do not apply to C character arrays.
Convert valid text with int.Parse
Run this complete example in a C# console application. Pass the variable text to int.Parse; quoting its name would pass the word "text" instead.
using System;
class Program
{
static void Main()
{
string text = "83";
int number = int.Parse(text);
Console.WriteLine(number);
}
}
Output: 83.
int.Parse throws FormatException for text such as "pizza", OverflowException for a value outside the int range, and ArgumentNullException for a null string.
Handle invalid input with int.TryParse
int.TryParse returns a Boolean that tells you whether conversion succeeded. Check that return value before using the output integer.
using System;
class Program
{
static void Main()
{
string text = "pizza";
if (int.TryParse(text, out int number))
{
Console.WriteLine(number);
}
else
{
Console.WriteLine("Enter a whole number within the int range.");
}
}
}
Output: Enter a whole number within the int range. Change text to "26" to print 26.
With the string overload shown here, a failed conversion sets number to zero. Zero is also a valid input, so testing number == 0 cannot tell you whether conversion failed.
Which strings can be converted?
The default overload accepts decimal digits, a leading sign, and surrounding whitespace using the current culture. It rejects empty strings, null, fractional text such as "3.5", and values outside -2,147,483,648 through 2,147,483,647. Thousands separators are not accepted by the default integer style.
For data with a defined format, use an overload that accepts NumberStyles and an IFormatProvider. Choose the style and culture to match your input rather than removing punctuation blindly.
Continue learning
Use your parsed number in multiplication and division, or check whether it is even or odd.
References
Microsoft documents the accepted formats and failure behavior in Int32.TryParse and Int32.Parse.