int.TryParse vs. other methods for determining if

2019-07-12 18:33发布

When using the char datatype is there any reason one should use int.TryParse

int.TryParse(inputChar.ToString(), NumberStyles.Integer, 
                             CultureInfo.InvariantCulture, out curNum)

vs.

inputChar - '0'

And checking if the result is between 0-9?

标签: c# tryparse
3条回答
相关推荐>>
2楼-- · 2019-07-12 19:07

If you want to check if a char is a digit you should use Char.IsDigit:

if (Char.IsDigit(inputChar))
{ 
    // ...
}
查看更多
男人必须洒脱
3楼-- · 2019-07-12 19:14

Well, two reasons why I would always use TryParse

  1. Using a well-tested library function is always better than re-inventing the wheel.
  2. The world outside the US doesn't speak "ASCII" - so there might be cases when the character code for 0 is not the smallest for a digit. In that case '9' - '0' != 9;. This is a might be. And because I'm too lazy to google this I'm on the safe side using TryParse :-)
查看更多
祖国的老花朵
4楼-- · 2019-07-12 19:21

That's only about code clarity. int.TryParse clearly states its intent - I want to parse the string as number, if possible. It's relatively fast and safe.

If you find yourself getting stuck on TryParses, you can always write your own parsing. In some cases, it can save significant amount of time. For example, I've done such an implementation when parsing DBFs, which otherwise induced a lot of overhead from parsing bytes to strings, and strings to ints. Directly converting from the stream to int saved a lot of allocations and time.

After all, if you don't want to use built-in methods, why use .NET at all? Why not write everything in machine code? :))

查看更多
登录 后发表回答