Skip to content

/commands/csharp/convert-string-to-int

c# convert string to int: int.Parse vs int.TryParse vs Convert.ToInt32

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash) · 10.0.401updated
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

bash
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.cs

Output

"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

MethodInvalid textnullUse when
int.TryParse(s, out var n)Returns falseReturns falseInput may be invalid: forms, files, query strings
int.Parse(s)FormatException / OverflowExceptionArgumentNullExceptionInvalid input is a bug and should stop the program
Convert.ToInt32(s)FormatException / OverflowExceptionReturns 0Converting object values (for example from a database) of unknown type
int.TryParse(s, NumberStyles.X, culture, out n)Returns falseReturns falseThousands separators, hex, or a specific culture
long.TryParse / decimal.TryParseReturns falseReturns falseValues beyond the int range, or decimals

Pitfalls

  • Culture. Parse and TryParse without a culture use the current culture of the thread. For machine-readable data (config files, JSON, CSV), pass CultureInfo.InvariantCulture so a server set to another language parses the same way.
  • Ignoring the return value. int.TryParse(s, out var n); followed by using n silently treats invalid input as 0. Check the bool.
  • Out variable scope. out var n declares n in the enclosing scope; using a name that was never declared fails with CS0103.
  • Nullable warnings. Passing a string? to int.Parse produces a nullable warning (CS8604); TryParse accepts null and simply returns false.

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.

Sources