Sobes.tech
Junior — Middle

How do the behaviors of TryParse and Parse methods differ when string-to-number conversion fails?

sobes.tech AI

Answer from AI

The Parse method throws a FormatException or OverflowException if the string cannot be converted to a number, either because the format is incorrect or the value exceeds the type's limits.

The TryParse method, instead of throwing an exception, returns a boolean false if the conversion fails, and outputs the result in an out parameter. This allows you to avoid exception handling and write more efficient and safer code.

Example:

string input = "abc";
int number;

// Parse will throw an exception
// int result = int.Parse(input); // FormatException

// TryParse will return false without throwing an exception
bool success = int.TryParse(input, out number);
if (success)
{
    Console.WriteLine($"Converted number: {number}");
}
else
{
    Console.WriteLine("Conversion failed");
}