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条回答
萌系小妹纸
2楼-- · 2019-01-22 17:31

Is it exceptional for the conversion to sometimes fail, or is it expected and normal that the conversion will sometimes fail? If the former, use an exception. If the latter, avoid exceptions. Exceptions are called "exceptions" for a reason; you should only use them to handle exceptional circumstances.

查看更多
Root(大扎)
3楼-- · 2019-01-22 17:35

Catching an Exception has more overhead, so I'll go for TryParse.

Plus, TryParse method does not throw an exception if the conversion fails. It eliminates the need to use exception handling to test for a FormatException in the event that s is invalid and cannot be successfully parsed.

That last part copy-pasted from here

查看更多
干净又极端
4楼-- · 2019-01-22 17:37

First, by far. As George said, second is coding by exception and has major performance impacts. And performance should be a concern, always.

查看更多
登录 后发表回答