/commands/csharp/convert-string-to-int
c# convert string to int: int.Parse vs int.TryParse vs Convert.ToInt32
- tool
- C#
- versions
- .NET Framework 2.0+ (TryParse), .NET 10
- os
- any
int.TryParse(text, out int value) converts a string to an int without throwing: it returns true and sets value on success, false (and value = 0) otherwise. Use it for user input and files. int.Parse(text) returns the number directly but throws FormatException or OverflowException on bad input, and Convert.ToInt32(text) behaves like Parse except that it returns 0 for null.
Compare the three
cat > parse.cs <<'EOF'
using System.Globalization;
string?[] inputs = ["42", " -7 ", "+5", "3.5", "1,000", "abc", "", "2147483648", null];
foreach (var s in inputs)
{
var shown = s is null ? "null" : $"\"{s}\"";
var ok = int.TryParse(s, out var n);
string parse;
try { parse = int.Parse(s!).ToString(); } catch (Exception e) { parse = e.GetType().Name; }
string toInt32;
try { toInt32 = Convert.ToInt32(s).ToString(); } catch (Exception e) { toInt32 = e.GetType().Name; }
Console.WriteLine($"{shown,-13} TryParse={ok,-5} ({n,-3}) Parse={parse,-24} Convert={toInt32}");
}
Console.WriteLine(int.Parse("1,000", NumberStyles.AllowThousands, CultureInfo.InvariantCulture));
Console.WriteLine(int.TryParse("ff", NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var hex) ? hex : -1);
EOF
dotnet run parse.csOutput
"42" TryParse=True (42 ) Parse=42 Convert=42 " -7 " TryParse=True (-7 ) Parse=-7 Convert=-7 "+5" TryParse=True (5 ) Parse=5 Convert=5 "3.5" TryParse=False (0 ) Parse=FormatException Convert=FormatException "1,000" TryParse=False (0 ) Parse=FormatException Convert=FormatException "abc" TryParse=False (0 ) Parse=FormatException Convert=FormatException "" TryParse=False (0 ) Parse=FormatException Convert=FormatException "2147483648" TryParse=False (0 ) Parse=OverflowException Convert=OverflowException null TryParse=False (0 ) Parse=ArgumentNullException Convert=0 1000 255
Surrounding spaces and a leading sign are accepted by the default style; decimals, thousands separators, empty strings and values beyond int.MaxValue are rejected. Passing NumberStyles and a culture widens what is accepted.
Which one to use
| Method | Invalid text | null | Use when |
|---|---|---|---|
| int.TryParse(s, out var n) | Returns false | Returns false | Input may be invalid: forms, files, query strings |
| int.Parse(s) | FormatException / OverflowException | ArgumentNullException | Invalid input is a bug and should stop the program |
| Convert.ToInt32(s) | FormatException / OverflowException | Returns 0 | Converting object values (for example from a database) of unknown type |
| int.TryParse(s, NumberStyles.X, culture, out n) | Returns false | Returns false | Thousands separators, hex, or a specific culture |
| long.TryParse / decimal.TryParse | Returns false | Returns false | Values beyond the int range, or decimals |
Pitfalls
- Culture.
ParseandTryParsewithout a culture use the current culture of the thread. For machine-readable data (config files, JSON, CSV), passCultureInfo.InvariantCultureso a server set to another language parses the same way. - Ignoring the return value.
int.TryParse(s, out var n);followed by usingnsilently treats invalid input as0. Check thebool. - Out variable scope.
out var ndeclaresnin the enclosing scope; using a name that was never declared fails with CS0103. - Nullable warnings. Passing a
string?toint.Parseproduces a nullable warning (CS8604);TryParseacceptsnulland simply returnsfalse.
Confirm it worked
Print the bool result together with the value, as above, and test the edge cases your input can contain: empty string, spaces, a sign, a value just above int.MaxValue.
FAQ
What is the difference between int.Parse and Convert.ToInt32?
Convert.ToInt32(string) calls int.Parse for non-null strings, but returns 0 for null instead of throwing ArgumentNullException. Both throw FormatException for text that is not a number.
Does int.TryParse accept spaces?
Leading and trailing white space is allowed with the default NumberStyles.Integer, so " 42 " parses. A thousands separator such as 1,000 is not allowed unless you pass NumberStyles.AllowThousands.
How do I parse a number with a decimal point?
Use decimal.TryParse or double.TryParse. int parsing rejects "3.5"; if you need an int afterwards, round the decimal value explicitly.