skip to content
Khalid Abuhakmeh logo Khalid Abuhakmeh

Convert a String to an Int in C#

Three reliable ways to convert a string to an int in C# — int.Parse, int.TryParse, and Convert.ToInt32 — plus which one to reach for and why.

6 min read Updated

Converting a string to an int in C# is a daily chore, whether the value comes from user input, a query string, a config file, or a CSV. I’ll walk through the three built-in options—int.TryParse, int.Parse, and Convert.ToInt32—and when to reach for each.

To convert a string to an int in C#, call int.TryParse(input, out int number) for input you don’t fully trust—it returns true on success and false on failure without throwing. When the string is guaranteed to be a valid number, int.Parse("42") returns the int directly. Use Convert.ToInt32 only when you want null to become 0.

int.TryParse : Convert a String Safely

When dealing with untrusted input, you’ll want to lean on int.TryParse. The method follows the typical TryX pattern found in other .NET APIs. On success, the method returns true and an out parameter containing the resulting value. On failure, it returns false and sets the out parameter to 0. This makes it easy to handle both success and failure cases without exceptions. Always branch on the bool return value, though: a failed parse leaves number at 0, which is indistinguishable from successfully parsing "0", so never infer success from the out value alone. It’s the same approach I reach for when reading and converting QueryCollection values in ASP.NET.

if (int.TryParse(input, out int number))
{
// success — use `number`
}
else
{
// failure — `number` is 0 here, but 0 is also a valid parse of "0",
// so always check the bool, never the out value alone
}

int.TryParse is the best option for most developers when converting strings to integers, especially when the input may not be guaranteed to be valid.

int.Parse : Simple, but It Throws

When working with trusted input, int.Parse is your most straightforward option. Since you’re a developer either controlling the input or guaranteeing its format through strict validation, you can use int.Parse without worrying about exceptions (even though you should always worry about exceptions). Although, there are some edge cases as you can see in the example below.

int number = int.Parse("42");
// number == 42
// int.Parse("4a2") -> throws FormatException
// int.Parse(null) -> throws ArgumentNullException
// int.Parse("9999999999") -> throws OverflowException

Use int.Parse for quick prototypes and code samples for non-production code.

Convert.ToInt32 : The Null-Tolerant Option

You may be tempted to use the Convert class and its Convert.ToInt32 method. The key difference between the other approaches is this method treats null as 0 instead of throwing an exception. This can be useful in scenarios where a missing value should be interpreted as zero, but it can also lead to unexpected outcomes and bugs that will make you pull your hair out.

int a = Convert.ToInt32("42"); // 42
int b = Convert.ToInt32(null); // 0 (no exception!)
// Convert.ToInt32("4a2") -> throws FormatException

Leave this method in the toolbox and favor the other two approaches for more predictable behavior.

Why Does String-to-Int Parsing Fail?

Outside of parsing strings into integers, the biggest pain point you need to watch for is culture and format. By default, parsing uses the current culture and NumberStyles.Integer, which allows for a leading sign and surrounding whitespace only. This means that strings like "1,304" will fail unless you explicitly allow thousands separators and provide a culture. The .NET docs on parsing numeric strings cover the full set of NumberStyles rules.

You can use NumberStyles and CultureInfo to handle these cases properly. For example, the following code demonstrates how to parse a string with a thousands separator:

using System.Globalization;
int.TryParse("1,304", out var fails); // false -> 0
int.TryParse("1,304",
NumberStyles.Integer | NumberStyles.AllowThousands,
CultureInfo.InvariantCulture,
out var works); // true -> 1304

If you’re hoping to deploy your code into multiple regions or region agnostic environments, consider using CultureInfo.InvariantCulture to ensure consistent parsing behavior across different locales. Culture sneaks into more string work than you’d expect—I ran into it again while writing a string numeric comparer with .NET 9.

Which Should You Use?

So given your options, which of these should you use? From personal experience, use int.TryParse by default. It is the safest and most efficient option for handling untrusted input, and it avoids exceptions that can disrupt your application’s flow. Use int.Parse only when you are certain the input is valid, and reserve Convert.ToInt32 for cases where you want to treat null as 0. Just remember to always consider the culture and format of the input string to avoid unexpected parsing issues.

Here is a quick reference for which method to use based on your input scenario:

Input Scenario Recommended Method
Untrusted input int.TryParse
Trusted / guaranteed int.Parse
Need null to mean 0 Convert.ToInt32

Frequently Asked Questions

How do I convert a string to an int in C#?

Use int.TryParse(input, out int number) for input you don’t fully trust: it returns true on success and false on failure without throwing. When you’re certain the string is a valid number, int.Parse("42") returns the int directly. Both live on the int (System.Int32) type and require no extra packages.

What is the difference between int.Parse and int.TryParse?

int.Parse returns the parsed int but throws an exception (FormatException, ArgumentNullException, or OverflowException) when the string isn’t a valid number. int.TryParse never throws for bad input; it returns a bool indicating success and sets an out parameter to the result (or 0 on failure). Use TryParse for user input and Parse only when the value is guaranteed valid.

How do I convert a string to an int without exceptions?

Call int.TryParse and branch on its bool return value. Because it reports failure through the return value instead of throwing, it’s the safest choice for untrusted input like query strings, form fields, or CSV cells. Always check the bool: a failed parse leaves the out value at 0, which is indistinguishable from successfully parsing "0".

Why does int.Parse fail on a string like “1,304”?

By default, parsing uses the current culture with NumberStyles.Integer, which doesn’t allow thousands separators. Pass NumberStyles.AllowThousands (combined with NumberStyles.Integer) and a CultureInfo to accept grouped numbers: int.TryParse("1,304", NumberStyles.Integer | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out var value). Use CultureInfo.InvariantCulture for consistent behavior across regions.

What does Convert.ToInt32 do with null?

Convert.ToInt32(null) returns 0 instead of throwing, unlike int.Parse, which throws an ArgumentNullException. That null tolerance is occasionally handy, but it can also hide bugs, so prefer int.TryParse or int.Parse unless you specifically want a missing value to mean zero.

If you want a quick reference for other everyday types and conversions, bookmark my C# cheat sheet.

Thanks for reading! If you found this post helpful, you might also enjoy converting a C# object to almost any format and my other posts on C# and .NET development.

Comments

Related Posts