C# TryParse Overview

String type

Many TryParse methods are available. Let's suppose you have a string value and want to convert it to another type that its characters represent. But your strings might be invalid. With TryParse methods we reduce the impact of these errors.

This C# page covers various TryParse methods in the .NET Framework.

Concept

Question and answer

Why does the .NET Framework use TryParse? The Parse method performs the same task but has a different error signaling mechanism: it throws exceptions. Unfortunately, exceptions are slow when they occur. TryParse is a way for you to indicate that errors are expected and should be handled in a faster way. You can test a boolean instead of using an exception handling construct.

Parse numeric values

First, there are many examples of using TryParse for converting a string into an int, short, double or decimal on this site. If the input value is invalid, no exception will be thrown; TryParse returns false.

int.TryParse decimal.TryParse

Enum.TryParse

The Enum.TryParse method lets you parse a string value into a enumerated constant. This can be useful for reading in enums from a settings file that may contain errors.

Enum.TryParse

DateTime

DateTime type illustration

If you have a string value that may or may not contain a valid DateTime, you can use DateTime.TryParse or DateTime.TryParseExact. The Exact method allows you to specify the exact formatting pattern that the string should follow for parsing to succeed.

DateTime.TryParse DateTime.TryParseExact

TimeSpan.TryParse

It is also possible to parse a TimeSpan instance from a string value. To do this, use the TimeSpan.TryParse method.

TimeSpan.TryParse

Summary

.NET Framework information

The TryParse methods in the .NET Framework adhere to the Tester-Doer pattern. They first test the value for correctness, and if that test succeeds, then they do the parsing. They have a different, and faster, error handling mechanism than the Parse methods.

String Type
.NET