What is the difference (both in terms of correctness and performance) between doing the following comparisons.
int a = 100;
string b = "100";
if (a == Convert.ToInt16(b))
//Do something
if (a.ToString() == b)
//Do Something
If I have a string value that is always an int (say for storing an int in a hidden field on a webpage) I have always compared both values as integers because that is what the data is representing, but I would like a more technical reason.
Comparing strings somewhat works for equality and inequality, but not for other comparisons.
For instance, a < Convert.ToInt16(b)
is not the same thing as a.ToString() < b
.
For that reason alone, I personally always prefer comparing numbers instead of strings.
If the string is 0100
, the second option will incorrectly return false
If the string happens to not contain an integer (eg, an attacker modified it), the first option will throw an exception
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With