Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C#

2 Answers

Tsenko Aleksiev
Tsenko Aleksiev
3,819 Points

Well, as far as I know Parse throws 3 exceptions ( I have read it somewhere ):

  • the input is null;
  • the input is not in valid format;
  • the input contains a number that produces an overflow;

TryParse just gives you a boolean if it fails to parse it, so I think it's better to use TryParse in most cases and Parse if you are really sure that it's going to be a number. With TryParse you can check if the input is a number or not and throw a message if it fails, the Parse method will directly break...I think. Hope I helped :)

I just wanted to expand on this a little because this is already correct - in the case of success, they do the same thing. In the case of failure, Parse() will return why it failed, while TryParse() will just return false. It mainly depends on the context - do you need to know specifically why it failed? Which is better overall is pretty subjective, but in general TryParse is great if you just need to check whether the value is an int or not or if you don't need (or want) it to throw an exception if it fails, while Parse is good for when you need to know why the parsing failed - format, null, etc.

If you're curious, you can view the MSDN docs for both of them here:

Tsenko Aleksiev
Tsenko Aleksiev
3,819 Points

Katie is the best answer - she said it like a pro, me - i'm still a newbie and this is something that I have just heard or read somewhere. Katie 10 pts from me for the answer :)