int.TryParse vs. other methods for determining if

2019-07-12 18:19发布

问题:

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?

回答1:

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

if (Char.IsDigit(inputChar))
{ 
    // ...
}


回答2:

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 :-)


回答3:

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? :))



标签: c# tryparse