When to use Parse vs TryParse in C#

Parse() and TryParse() both convert strings to other types, but handle failures differently. Parse() throws an exception on invalid input, while TryParse() returns false and uses an out parameter for the result.

Use TryParse() when dealing with user input or untrusted data where invalid values are expected. Use Parse() when you're confident the string is valid or want an exception to propagate.

TryParse() is more performant when invalid input is common, as it avoids the overhead of exception handling.

C# Example Code
using System;

public class ParseVsTryParse
{
    public static void Main(string[] args)
    {
        // Parse() - throws exception on failure
        string validNumber = "123";
        int number1 = int.Parse(validNumber);
        Console.WriteLine($"Parsed successfully: {number1}");

        // Parse() with invalid input causes exception
        try
        {
            string invalidNumber = "abc";
            int number2 = int.Parse(invalidNumber);  // Throws FormatException
        }
        catch (FormatException ex)
        {
            Console.WriteLine($"Parse() failed: {ex.Message}");
        }

        // TryParse() - returns bool, no exception
        string userInput = "456";
        if (int.TryParse(userInput, out int result))
        {
            Console.WriteLine($"TryParse succeeded: {result}");
        }
        else
        {
            Console.WriteLine("TryParse failed");
        }

        // TryParse() with invalid input
        string badInput = "xyz";
        if (int.TryParse(badInput, out int badResult))
        {
            Console.WriteLine($"Parsed: {badResult}");
        }
        else
        {
            Console.WriteLine($"Cannot parse '{badInput}' - using default value");
            badResult = 0;  // Set default
        }

        // Different types
        Console.WriteLine("\nOther types:");

        // Double
        if (double.TryParse("3.14", out double pi))
        {
            Console.WriteLine($"Double: {pi}");
        }

        // DateTime
        if (DateTime.TryParse("2024-03-15", out DateTime date))
        {
            Console.WriteLine($"Date: {date:yyyy-MM-dd}");
        }

        // Boolean
        if (bool.TryParse("true", out bool flag))
        {
            Console.WriteLine($"Boolean: {flag}");
        }

        // Practical pattern: provide default value
        string maybeNumber = "not a number";
        int finalValue = int.TryParse(maybeNumber, out int parsed) ? parsed : -1;
        Console.WriteLine($"Final value: {finalValue}");
    }
}