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

2019-01-22 16:48发布

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

9条回答
Rolldiameter
2楼-- · 2019-01-22 17:15

If it is indeed expected that the conversion will sometimes fail, I like to use int.TryParse and such neatly on one line with the conditional (Ternary) operator, like this:

int myInt = int.TryParse(myString, out myInt) ? myInt : 0;

In this case zero will be used as a default value if the TryParse method fails.

Also really useful for nullable types, which will overwrite any default value with null if the conversion fails.

查看更多
贪生不怕死
3楼-- · 2019-01-22 17:21

Personally, I'd prefer:

if (int.TryParse(string, out num))
{
   ...
} 
查看更多
我想做一个坏孩纸
4楼-- · 2019-01-22 17:21

Something else to keep in mind is that exceptions are logged (optionally) in the Visual Studio debug/output window. Even when the performance overhead of exceptions might be insignificant, writing a line of text for each exception when debugging can slow things right down. More noteworthy exceptions might be drowned amongst all the noise of failed integer parsing operations, too.

查看更多
ゆ 、 Hurt°
5楼-- · 2019-01-22 17:23

The first! You should not code by exception.

you could shorten it to

if (int.TryParse(string, out num))

查看更多
来,给爷笑一个
6楼-- · 2019-01-22 17:27

The first. The second is considered coding by exception.

查看更多
虎瘦雄心在
7楼-- · 2019-01-22 17:28

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 procudes an overflow

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

As always, context is king.

查看更多
登录 后发表回答