C# string to int conversion tutorial
last modified October 18, 2026
In this article we show how to convert strings to integers in C#. We use
int.Parse, int.TryParse, and the methods of the
Convert class.
C# string to int conversion
String to integer conversion is a type conversion in which a string is changed into an integer. This kind of conversion is very common because we receive values from forms, command line arguments, configuration files, and databases as strings, even if the values are integers.
There are three main options:
int.Parseconverts a string and throws an exception if the conversion fails.int.TryParseconverts a string and returnsfalseif the conversion fails; it never throws for bad input.Convert.ToInt32converts many types, including strings. For anullstring, it returns 0; for malformed text, it throws.
int is the C# keyword for System.Int32, so
int.Parse and Int32.Parse are the same method. Other
numeric types have equivalent methods; for instance long.TryParse or
double.Parse.
As a rule of thumb, use TryParse for data that may be invalid, such
as user input, and Parse when invalid data is a bug that should stop
the program.
C# string to int with Convert.ToInt32
The Convert class contains methods for converting one base data type
to another.
| Numeric type | Method |
|---|---|
| decimal | ToDecimal |
| float | ToSingle |
| double | ToDouble |
| short | ToInt16 |
| int | ToInt32 |
| long | ToInt64 |
| ushort | ToUInt16 |
| uint | ToUInt32 |
| ulong | ToUInt64 |
The table lists the methods that convert strings to various numeric types. The
Convert.ToInt32 method converts a value to a 32-bit signed integer.
string applesInBasket = "12";
string baskets = "4";
int total = Convert.ToInt32(applesInBasket) * Convert.ToInt32(baskets);
Console.WriteLine($"There are total of {total} apples");
string? missing = null;
Console.WriteLine(Convert.ToInt32(missing));
Console.WriteLine(Convert.ToInt32("ff", 16));
Console.WriteLine(Convert.ToInt32("1010", 2));
In the example, we multiply two integer values that we have initially as strings.
int total = Convert.ToInt32(applesInBasket) * Convert.ToInt32(baskets);
We convert the strings and compute the expression.
string? missing = null; Console.WriteLine(Convert.ToInt32(missing));
Unlike int.Parse, which throws an ArgumentNullException,
Convert.ToInt32 turns null into 0. This can hide
missing data, so it is usually better to handle null explicitly.
Console.WriteLine(Convert.ToInt32("ff", 16));
Console.WriteLine(Convert.ToInt32("1010", 2));
The overload with a second argument parses a string in base 2, 8, 10, or 16.
$ dotnet run There are total of 48 apples 0 255 10
C# string to int with int.Parse
The int.Parse method converts the string representation of a number
to its 32-bit signed integer equivalent. It throws an exception if the conversion
fails:
ArgumentNullException- the string isnullFormatException- the string is not a valid numberOverflowException- the number does not fit into anint
string[] values = ["2342", "-17", " 42 ", "23423453263456345", "12.5", "abc", ""];
foreach (var val in values)
{
try
{
int num = int.Parse(val);
Console.WriteLine($"Converted '{val}' to {num}");
}
catch (FormatException)
{
Console.WriteLine($"Unable to convert '{val}'");
}
catch (OverflowException)
{
Console.WriteLine($"'{val}' is out of range of the int type");
}
}
try
{
int.Parse(null!);
}
catch (ArgumentNullException e)
{
Console.WriteLine(e.ParamName);
}
In the example, we parse several strings and handle the possible exceptions.
$ dotnet run Converted '2342' to 2342 Converted '-17' to -17 Converted ' 42 ' to 42 '23423453263456345' is out of range of the int type Unable to convert '12.5' Unable to convert 'abc' Unable to convert '' s
Leading and trailing white space and a leading sign are allowed by default. A
decimal point is not, and neither is an empty string. The huge number cannot be
stored in 32 bits, so OverflowException is thrown. The last line is
the name of the parameter reported by the ArgumentNullException.
C# string to int with int.TryParse
The int.TryParse method converts the string representation of a
number to its 32-bit signed integer equivalent. The boolean return value
indicates whether the operation succeeded, and the converted value is returned in
the out parameter. No exception is thrown for malformed or
null input.
string[] values = ["2342", "-17", "abc", "99999999999", "12.5", null!];
foreach (var val in values)
{
if (int.TryParse(val, out int j))
{
Console.WriteLine($"'{val}' -> {j}");
}
else
{
Console.WriteLine($"'{val}' could not be parsed");
}
}
int.TryParse("oops", out int result);
Console.WriteLine($"result after failure: {result}");
int port = int.TryParse("not a number", out int p) ? p : 8080;
Console.WriteLine(port);
The example tries to convert several strings.
if (int.TryParse(val, out int j))
We declare the output variable inline, in the call. The condition checks the returned boolean.
int.TryParse("oops", out int result);
Console.WriteLine($"result after failure: {result}");
When the conversion fails, the output variable is set to 0. Always check the return value; do not rely on the zero to detect an error, because "0" parses to zero as well.
int port = int.TryParse("not a number", out int p) ? p : 8080;
A conditional expression gives a compact way to fall back to a default value.
$ dotnet run '2342' -> 2342 '-17' -> -17 'abc' could not be parsed '99999999999' could not be parsed '12.5' could not be parsed '' could not be parsed result after failure: 0 8080
C# NumberStyles
By default, int.Parse accepts white space around the number and a
leading sign. The NumberStyles enumeration lets us allow other
formats, such as thousands separators, hexadecimal digits, or parentheses, or
restrict the input to digits only.
using System.Globalization;
Console.WriteLine(int.Parse("1,234,567", NumberStyles.AllowThousands, CultureInfo.InvariantCulture));
Console.WriteLine(int.Parse("FF", NumberStyles.HexNumber));
Console.WriteLine(int.Parse(" -42 ", NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite | NumberStyles.AllowLeadingSign));
Console.WriteLine(int.Parse("(100)", NumberStyles.AllowParentheses));
Console.WriteLine(int.Parse("12", NumberStyles.None));
Console.WriteLine(int.TryParse("12 ", NumberStyles.None, null, out _));
The examples show several styles.
Console.WriteLine(int.Parse("FF", NumberStyles.HexNumber));
HexNumber parses hexadecimal digits, without the 0x
prefix.
Console.WriteLine(int.Parse("(100)", NumberStyles.AllowParentheses));
Parentheses denote a negative number in accounting notation.
Console.WriteLine(int.TryParse("12 ", NumberStyles.None, null, out _));
NumberStyles.None permits digits only, so the trailing space makes the
parsing fail. This is useful for strict validation.
$ dotnet run 1234567 255 -42 -100 12 False
C# string to int and culture
Parsing is culture sensitive. The group separator, for instance, is a comma in
the US and a period in Germany. When we do not pass an
IFormatProvider, the current culture of the thread is used, so the
same code can behave differently on different machines.
using System.Globalization;
var de = new CultureInfo("de-DE");
var us = new CultureInfo("en-US");
// the group separator is culture specific
Console.WriteLine(int.TryParse("1,000", NumberStyles.AllowThousands, us, out int a) ? a : -1);
Console.WriteLine(int.TryParse("1.000", NumberStyles.AllowThousands, us, out int b) ? b : -1);
Console.WriteLine(int.TryParse("1.000", NumberStyles.AllowThousands, de, out int c) ? c : -1);
Console.WriteLine(int.TryParse("1,000", NumberStyles.AllowThousands, de, out int d) ? d : -1);
// when data comes from files or protocols use the invariant culture
Console.WriteLine(int.Parse("123", CultureInfo.InvariantCulture));
We parse the same digits with two cultures.
$ dotnet run 1000 -1 1000 -1 123
Each culture accepts only its own separator. For data that comes from files,
network protocols, or configuration, pass
CultureInfo.InvariantCulture so that the result does not depend on
the machine's settings.
C# string to int with spans
Parsing methods accept ReadOnlySpan<char> and, since .NET 8,
ReadOnlySpan<byte> with UTF-8 text. This lets us parse a part of
a larger string, or raw network data, without allocating intermediate strings.
string line = "id=42;count=7;";
ReadOnlySpan<char> span = line;
int eq = span.IndexOf('=');
int semi = span.IndexOf(';');
int id = int.Parse(span[(eq + 1)..semi]);
Console.WriteLine(id);
// UTF-8 bytes can be parsed without creating a string
ReadOnlySpan<byte> utf8 = "12345"u8;
Console.WriteLine(int.Parse(utf8));
Console.WriteLine(int.TryParse("77".AsSpan(), out int n) ? n : -1);
We parse a number from the middle of a string and from a UTF-8 literal.
int id = int.Parse(span[(eq + 1)..semi]);
Slicing a span does not copy the data. The slice contains only the digits between the equals sign and the semicolon.
ReadOnlySpan<byte> utf8 = "12345"u8;
The u8 suffix creates a UTF-8 byte literal.
$ dotnet run 42 12345 77
C# convert a collection of strings
We often need to convert many strings and skip the invalid ones.
string[] words = ["10", "x", "30", "", "50", "7.5"];
List<int> numbers = words
.Select(w => int.TryParse(w, out int n) ? (int?)n : null)
.Where(n => n.HasValue)
.Select(n => n!.Value)
.ToList();
Console.WriteLine(string.Join(", ", numbers));
Console.WriteLine(numbers.Sum());
Console.WriteLine(Sum<int>(["1", "2", "3"]));
Console.WriteLine(Sum<double>(["1.5", "2.5"]));
Console.WriteLine(Sum<long>(["9000000000", "1"]));
static T Sum<T>(IEnumerable<string> items) where T : System.Numerics.INumber<T>
{
T sum = T.Zero;
foreach (var item in items)
{
sum += T.Parse(item, System.Globalization.CultureInfo.InvariantCulture);
}
return sum;
}
We turn the valid strings of an array into numbers. The generic method uses the
static abstract T.Parse of the INumber<T>
interface, which makes it work for any numeric type.
.Select(w => int.TryParse(w, out int n) ? (int?)n : null) .Where(n => n.HasValue) .Select(n => n!.Value)
We project every string to a nullable integer, drop the failures, and unwrap the values.
$ dotnet run 10, 30, 50 90 6 4 9000000001
C# string to int overflow
A value that does not fit into 32 bits fails to parse. We can use a wider type.
using System.Numerics;
string big = "23423453263456345";
if (!int.TryParse(big, out _))
{
Console.WriteLine("does not fit into int");
}
if (long.TryParse(big, out long l))
{
Console.WriteLine($"long: {l}");
}
BigInteger b = BigInteger.Parse("123456789012345678901234567890");
Console.WriteLine(b * 2);
string?[] inputs = ["12", "1" + new string('0', 12)];
foreach (var s in inputs)
{
Console.WriteLine(int.TryParse(s, out int v) ? v.ToString() : $"{s} is too big");
}
The number 23423453263456345 does not fit into an int (maximum
2,147,483,647), but it fits into a long. For arbitrarily large
integers, we use BigInteger.
$ dotnet run does not fit into int long: 23423453263456345 246913578024691357802469135780 12 1000000000000 is too big
Source
In this article we have shown how to convert strings to integers in C#.
Author
List all C# tutorials.