Parse v. TryParse

Kredns picture Kredns · Jan 22, 2009 · Viewed 110k times · Source

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?

Answer

Greg Beech picture Greg Beech · Jan 22, 2009

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.