Search code examples
c#.netparsingtype-conversiontryparse

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


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

Solution

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