Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

C# Parse vs TryParse: When to Use Each

Compare C# Parse and TryParse for string-to-number conversion, covering exception behavior, performance, and when to use each.

~4 min readC#
#C##string conversion#exception handling#TryParse
Comparison of C# Parse and TryParse methods for string to number conversion with error handling.

When converting a string to a number in C#, developers typically reach for int.Parse or int.TryParse. The choice between Parse and TryParse affects how failures are handled, how readable the code is, and how much exception overhead you pay. The two methods look similar, but they behave differently when the input is not a valid number.

The Core Difference: Exceptions vs Boolean Results

Parse and TryParse both convert a string representation of a number into a numeric type. The critical difference is their failure behavior. Parse throws an exception for invalid input: FormatException when the string is malformed, OverflowException when the value is outside the target type's range, and ArgumentNullException when the input is null. TryParse does not throw for invalid input; it returns false and sets an out parameter to the type's default value.

csharp
string input = "123"; int number = int.Parse(input); // returns 123 string invalid = "abc"; int result; bool success = int.TryParse(invalid, out result); // success = false, result = 0

The out parameter receives the parsed value only when parsing succeeds. On failure, it gets the default value of the type, which is 0 for int. This behavior is consistent across the numeric types that implement TryParse.

How Parse Behaves on Invalid Input

Parse is straightforward: it either returns the parsed value or throws an exception. This makes it suitable when you are certain the input is valid, or when an invalid value should abort the current operation with an exception that propagates up the call stack.

csharp
string userInput = GetUserInput(); int age = int.Parse(userInput); // throws FormatException if not a number

The exception type gives more information about the failure. FormatException means the string was not in the expected format, OverflowException means the value fell outside the target type's range, and ArgumentNullException means the input was null. In many applications, throwing an exception for invalid user input is not ideal because it disrupts control flow and is expensive.

How TryParse Handles Failure Without Throwing

TryParse was introduced to avoid exception overhead in scenarios where invalid input is expected. It returns a boolean that indicates whether the conversion succeeded, and the parsed value is written to an out parameter. This pattern is common in user input validation, configuration parsing, and any situation where the data source cannot be trusted.

csharp
string input = "42"; if (int.TryParse(input, out int number)) { Console.WriteLine($"Parsed: {number}"); } else { Console.WriteLine("Invalid number"); }

The out variable can be declared inline since C# 7.0. This keeps the code compact and avoids a separate declaration. The method does not throw a FormatException or OverflowException, so you do not need a try-catch block around it.

Performance Considerations: Exception Cost vs Out Parameter

Exceptions are expensive in .NET. When an exception is thrown, the runtime captures information about the failure and unwinds the stack. If you parse many strings in a loop and a meaningful fraction are invalid, using Parse with try-catch can add avoidable overhead. TryParse avoids that overhead by reporting failure through a boolean and an out parameter.

If your inputs are already guaranteed valid, either method will work. Do not micro-optimize by choosing Parse unless profiling shows that parsing is a bottleneck.

Choosing Between Parse and TryParse in Real Code

The decision comes down to whether invalid input is an exceptional condition or a normal possibility. Use Parse when:

  • The input is guaranteed to be valid by the surrounding logic.
  • An invalid value represents a programming error that should surface as an exception.
  • You need the exception details for logging or debugging.

Use TryParse when:

  • The input comes from user input, configuration files, or external APIs.
  • You want to handle invalid values gracefully without exceptions.
  • You are parsing in a loop or high-throughput path where exceptions would be costly.

A common pattern is to use TryParse in the UI layer to validate user input, and Parse in internal code where the data has already been validated.

CriterionParseTryParse
Failure behaviorThrows FormatException or OverflowExceptionReturns false, sets out parameter to default
Exception overheadHigh on invalid inputNone for invalid input
Typical use caseValidated data, programming errorsUser input, untrusted data
Code readabilityRequires try-catch for invalid inputClean if/else pattern

Parsing Other Types and Custom Formats

The same Parse/TryParse pattern applies to all numeric types: double, decimal, float, long, short, byte, and the unsigned variants. Each type has its own Parse and TryParse overloads. For example, decimal.TryParse is useful when you need decimal precision for monetary values.

csharp
string priceText = "19.99"; if (decimal.TryParse(priceText, NumberStyles.Currency, CultureInfo.InvariantCulture, out decimal price)) { // use price }

Both methods also support overloads that accept a NumberStyles value and an IFormatProvider. These let you control which characters are considered valid, such as currency symbols, thousands separators, or decimal points. The TryParse overloads follow the same signature pattern and return false if the input does not match the specified style.

Common Mistakes When Using TryParse

One common mistake is ignoring the boolean return value and using the out variable anyway. If parsing fails, the out variable is set to the default value, which can lead to silent data corruption. Always check the return value before using the parsed result.

Another mistake is assuming TryParse handles null the same way as Parse. Both treat null as invalid input, but Parse throws ArgumentNullException, while TryParse returns false. If you need to distinguish a null input from a non-numeric string, check for null separately.

Finally, remember that TryParse does not catch exceptions from the formatting provider. If the IFormatProvider implementation itself throws, the exception propagates. In practice, this is rare, but it is worth knowing that TryParse only guarantees no exceptions for the parsing logic, not for the provider.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.