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
?
If you want to check if a
char
is a digit you should useChar.IsDigit
:Well, two reasons why I would always use
TryParse
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 usingTryParse
:-)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
TryParse
s, 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? :))