What is the difference between `Parse()` and `TryParse()` methods?

Beginner

Answer

Parse():

  • Throws exception if conversion fails
  • Returns converted value directly
  • Use when certain input is valid
    TryParse():
  • Returns boolean indicating success/failure
  • Uses out parameter for converted value
  • Use when input validity is uncertain
// Parse - throws exception on failure
try
{
    int value1 = int.Parse("123");
    int value2 = int.Parse("abc"); // Throws FormatException
}
catch (FormatException ex) { }
// TryParse - safe conversion
if (int.TryParse("123", out int value3))
{
    // Conversion successful
}
else
{
    // Conversion failed, value3 is 0
}