views:

1724

answers:

5
+9  Q: 

Parse v. TryParse

What is the difference between parse and TryParse?

int number = int.Parse(textBoxNumber.Text);

// The Try-Parse Method
int.TryParse(textBoxNumber.Text, out number);

Is there some form of error-checking like a Try-Catch Block?

+4  A: 

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)
M4N
+2  A: 

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.

Ray Booysen
+1  A: 

TryParse does not return the value, it returns a status code to indicate whether the parse succeeded (and doesn't throw an exception).

Mark Brittingham
TryParse does return the value through parameter two which is specified with the out keyword.
Christian Madsen
@Christian Madsen - Thanks.
Mark Brittingham
+17  A: 

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.

Greg Beech
"internally the Parse method will call TryParse"Except that Parse pre-dates TryParse by several versions. Of course, they could have moved the core implementation to TryParse...
Joel Coehoorn
@Joel - I assumed they would have moved the implementation, but I just had a look with reflector and they are separate implementations with *exactly* the same code other than one has 'throw ...' and one has 'return false'. I wonder why they aren't consolidated?!
Greg Beech
Although, thinking about it, Parse throws a number of different exceptions so if all it had was a bool from TryParse then it wouldn't know which one to throw.
Greg Beech
+1  A: 

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.

Gulzar
TryParse will throw an exception if you pass null in for most integral TryParse methods.
Ray Booysen
Great link. I am surprised that no one hasn't yet started the "which one is best or which coding practice should be applied" discussion.
Christian Madsen