What is better: int.TryParse or try { int.Parse() } catch

renanleandrof picture renanleandrof · Feb 9, 2011 · Viewed 42.2k times · Source

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...
}

Answer

Fredrik Mörk picture Fredrik Mörk · Feb 9, 2011

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:

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

If you care about why it fails, then int.Parse is clearly the better choice.

As always, context is king.