I know.. I know... Performance is not the main concern here, but just for curiosity, what is better?
bool parsed = int.TryParse(string, out num); if (parsed) ...
OR
try { int.Parse(string); } catch () { do something... }
Parse() method throws an exception if it cannot parse the value, whereas TryParse() method returns a bool indicating whether it succeeded. However, TryParse does not return the value, it returns a status code to indicate whether the parse succeeded and does not throw exception.
The difference in both methods is in the way they react when the string you are trying to convert to integer can't be converted to an integer. And in such a circumstance, the int. Parse() method will throw an exception whereas the int. TryParse() will return a boolean value of false.
The Parse method returns the converted number; the TryParse method returns a boolean value that indicates whether the conversion succeeded, and returns the converted number in an out parameter. If the string isn't in a valid format, Parse throws an exception, but TryParse returns false .
Better is highly subjective. For instance, I personally prefer int.TryParse
, since I most often don't care why the parsing fails, if it fails. However, int.Parse
can (according to the documentation) throw three different exceptions:
If you care about why it fails, then int.Parse
is clearly the better choice.
As always, context is king.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With