Parse() returns the value and throws on invalid input, while TryParse() returns a bool for success and passes the value out through an out parameter.
Use Parse when invalid input means a bug, such as data your own code produced. Use TryParse for input you do not control, like user input or file contents. It avoids the cost of throwing and catching an exception for a failure you expect.
int.Parse throws a FormatException for text that is not a number, and an OverflowException when the number is out of range. On failure, TryParse sets the out value to its default, which is 0 for int. Most built-in value types have both methods, including DateTime and Guid.
// 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
}
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
The diagram below the answer is the concept . Jump to it ↓