The Try Pattern & Naming Convention in C#

The Try pattern (or Try* method convention) is a standard C# design pattern 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 (such as a user typing invalid text into a form or querying a key that may not exist), the Try pattern provides a clean, high-performance alternative.


1. Anatomy of a Try Method

A method following the Try pattern strictly adheres to three core rules:

  1. Name Prefix: The method name always begins with the word Try (e.g., TryParse, TryGetValue, TryDequeue).
  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 Example: int.TryParse

string input = "12345";
 
// Returns a boolean and passes the result back via 'out int result'
if (int.TryParse(input, out int result))
{
    Console.WriteLine($"Success! Parsed number: {result}");
}
else
{
    Console.WriteLine("Failed to parse.");
}