In C#, the Try pattern (often called the Try* method naming convention) is a standard design guideline used to perform operations that might fail without throwing an exception.

Throwing and catching exceptions is relatively expensive in terms of CPU cycles. If a failure is an expected outcome (like a user typing invalid text into a number field or looking up a key that might not exist), the Try pattern provides a clean, high-performance alternative.


Anatomy of a Try Method

A method following the Try pattern typically adheres to these three rules:

  1. Name Prefix: It starts with the word Try (e.g., TryParse, TryGetValue).
  2. Boolean Return Value: It returns a bool (true if the operation succeeded, false if it failed).
  3. Out Parameter: It uses the out keyword to pass back the resulting value if successful, or the type’s default value if it fails.

Quick Code Example:

string input = "12345";
 
// Instead of catching a FormatException:
if (int.TryParse(input, out int result))
{
    Console.WriteLine($"Success! Parsed number: {result}");
}
else
{
    Console.WriteLine("Failed to parse.");
}
 

Comprehensive List of Common .NET Try Methods

Because the .NET base class library is massive, there are dozens of Try* methods scattered across different namespaces. Below is a categorized list of the most widely used standard .NET Try methods:

1. Primitive Type & Struct Parsing

Used to convert string representations into primitives safely without throwing FormatException or OverflowException.

  • int.TryParse – Parses a standard 32-bit integer.
  • long.TryParse – Parses a 64-bit integer.
  • double.TryParse / float.TryParse / decimal.TryParse – Parses floating-point and decimal numbers.
  • bool.TryParse – Parses a boolean string ("True" / "False").
  • DateTime.TryParse / DateTimeOffset.TryParse – Parses date and time strings.
  • TimeSpan.TryParse – Parses time intervals.
  • Guid.TryParse – Parses globally unique identifiers (GUIDs).
  • Enum.TryParse<T> – Parses string values into an enum type.
  • IPAddress.TryParse – Parses network IP address strings.

2. Dictionaries & Lookups

Used to check for and retrieve a key-value pair simultaneously, avoiding a double lookup (checking ContainsKey followed by index access).

  • Dictionary<TKey, TValue>.TryGetValue – Retrieves a value by key from a standard dictionary if it exists.
  • ConcurrentDictionary<TKey, TValue>.TryGetValue – Thread-safe dictionary lookup.
  • ReadOnlyDictionary<TKey, TValue>.TryGetValue – Read-only dictionary lookup.

3. Collections (Queue & Stack)

Used to safely inspect or remove items from data structures when they might be completely empty.

  • Queue<T>.TryDequeue – Removes and returns the object at the beginning of the queue, returning false if empty.
  • Queue<T>.TryPeek – Returns the object at the beginning without removing it, returning false if empty.
  • Stack<T>.TryPop – Removes and returns the object at the top of the stack, returning false if empty.
  • Stack<T>.TryPeek – Returns the object at the top without removing it, returning false if empty.

4. Threading, Concurrency & Asynchronous Operations

Used in multi-threaded environments where resource acquisition or task coordination can time out or fail.

  • Monitor.TryEnter – Attempts to acquire an exclusive lock on an object within a specified time frame.
  • Thread.TrySetApartmentState – Attempts to change a thread’s apartment state before it starts.
  • CancellationToken.TryRegister (variant patterns) – Safe cancellation registration hooks.
  • BlockingCollection<T>.TryTake – Tries to add or take items from bounded thread-safe collections with timeouts.

.NET uses a standard signature for all methods that follow the Try naming convention. For any method named Something that returns a value of a specific type, its matching TrySomething method must return a bool to indicate success or failure and use an out parameter in place of the return value. For example: