Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

C# Parse vs TryParse: When to Use Each for String Conversion

Learn how to use Parse and TryParse in C# for safe string conversion, including error handling, culture, and performance tradeoffs.

~4 min readC#
#C##parsing#TryParse#string conversion
Illustration of C# Parse and TryParse methods converting strings to numbers with error handling.

In C#, parsing usually means converting a string into another type, such as an integer, double, DateTime, or enum. The .NET base class library provides the Parse and TryParse methods for this purpose. While they look similar, they behave differently on invalid input. Understanding that difference is the first step toward writing conversion code that handles invalid input predictably.

The Parse Method and Its Exceptions

The Parse method is straightforward: it takes a string and returns the converted value. If the string is not in a valid format, it throws an exception. For example:

csharp
string input = "42"; int number = int.Parse(input);

For numeric types, the exception type depends on the failure. A null string throws ArgumentNullException. An empty string or invalid format throws FormatException. A value that is too large or too small for the target type throws OverflowException.

This behavior is useful when you know the input is valid and you want the conversion to fail loudly. In a configuration file or a constant, Parse is often the right choice because an invalid value indicates a programming error that should surface immediately.

TryParse for Safe Conversion

When input comes from user entry, file contents, or external APIs, exceptions are not an ideal control flow. TryParse avoids throwing and instead returns a Boolean result. The converted value is written to an out parameter.

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

The out variable is declared inline. If parsing fails, result is set to the default value of the type, which is zero for numeric types. You should not rely on that default value; always check the return value before using the result.

TryParse does not throw for null, empty, or malformed strings. It returns false instead. This makes it a safer choice for user input and other untrusted sources.

Parsing with Culture and Format Providers

Many Parse and TryParse overloads accept an IFormatProvider. This is critical when the input uses a specific culture's number or date format. For example, the decimal separator differs between cultures: "1.5" in some cultures and "1,5" in others.

csharp
string input = "1,5"; double value = double.Parse(input, CultureInfo.GetCultureInfo("fr-FR"));

If you are parsing strings that come from a known culture, pass the corresponding CultureInfo. If the input is culture-invariant, such as a value stored in a file or a protocol, use CultureInfo.InvariantCulture. This prevents the current thread culture from changing the interpretation.

csharp
string input = "123.45"; double value = double.Parse(input, CultureInfo.InvariantCulture);

TryParse has corresponding overloads that accept the same culture and style options. Using the wrong culture is a common source of bugs that only appear on machines with different regional settings.

Parsing Numbers, Dates, and Enums

The Parse and TryParse pattern appears across many types. For dates, DateTime.Parse and DateTime.TryParse work similarly. They also accept culture and style arguments.

csharp
string dateInput = "2024-01-31"; if (DateTime.TryParse(dateInput, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime date)) { Console.WriteLine(date); }

For enums, Enum.Parse and Enum.TryParse convert a string to an enum value. Enum.TryParse is generic and can be used with any enum type.

csharp
enum Color { Red, Green, Blue } string colorInput = "Green"; if (Enum.TryParse<Color>(colorInput, out Color color)) { Console.WriteLine(color); }

Note that Enum.TryParse is case-sensitive by default. Use the overload with ignoreCase: true if you need case-insensitive matching.

Performance and Allocation Considerations

Parse and TryParse have similar performance characteristics for successful conversions. The main difference is that Parse may allocate an exception object when it fails, which is expensive. In a loop that processes many invalid strings, TryParse avoids that allocation and the associated stack unwinding.

csharp
// Avoid this in a loop for (int i = 0; i < inputs.Length; i++) { try { int value = int.Parse(inputs[i]); // process value } catch (FormatException) { // handle invalid input } }

The try/catch pattern is not only slower but also obscures the flow. TryParse expresses the success/failure branch directly.

When you parse the same format repeatedly, pass the appropriate NumberStyles and CultureInfo so the behavior is deterministic and does not depend on the current thread culture.

Choosing Between Parse and TryParse

The decision is not about which method is better overall, but about the context.

Use Parse when:

  • The input is guaranteed to be valid by the surrounding logic.
  • A failure indicates a bug that should stop execution.
  • You want the exception to propagate to a global handler.

Use TryParse when:

  • The input comes from a user, file, or network.
  • Invalid input is a normal condition that should be handled inline.
  • You want to avoid exception overhead in a high-throughput path.

A common middle ground is to use TryParse and then log or return a validation error. This keeps the control flow clean and avoids exceptions for expected failures.

Common Pitfalls and Culture Traps

One subtle issue is that int.Parse accepts leading and trailing whitespace by default. If you need to reject whitespace, use NumberStyles.None in the overload. Similarly, DateTime.Parse may accept dates in unexpected formats depending on the culture.

Another trap is parsing strings that contain a thousands separator. int.Parse("1,000") will throw a FormatException unless you specify NumberStyles.AllowThousands. This is often overlooked when reading numeric data from a file that was formatted for display.

csharp
string input = "1,000"; int value = int.Parse(input, NumberStyles.AllowThousands, CultureInfo.InvariantCulture);

For numeric parsing, when in doubt, use the overload that explicitly sets NumberStyles and CultureInfo. This makes the parsing behavior deterministic and independent of the machine's regional settings.

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.