Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse v. TryParse

Parse throws an exception if it cannot parse the value, whereas TryParse returns a bool indicating whether it succeeded.

TryParse does not just try/catch internally - the whole point of it is that it is implemented without exceptions so that it is fast. In fact the way it is most likely implemented is that internally the Parse method will call TryParse and then throw an exception if it returns false.

In a nutshell, use Parse if you are sure the value will be valid; otherwise use TryParse.


If the string can not be converted to an integer, then

  • int.Parse() will throw an exception
  • int.TryParse() will return false (but not throw an exception)

The TryParse method allows you to test whether something is parseable. If you try Parse as in the first instance with an invalid int, you'll get an exception while in the TryParse, it returns a boolean letting you know whether the parse succeeded or not.

As a footnote, passing in null to most TryParse methods will throw an exception.


TryParse and the Exception Tax

Parse throws an exception if the conversion from a string to the specified datatype fails, whereas TryParse explicitly avoids throwing an exception.