Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When comparing a string and an int, what is the difference between converting them both to a string vs converting them both to an int?

Tags:

c#

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.

like image 620
Curtis Avatar asked Dec 22 '22 10:12

Curtis


2 Answers

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.

like image 182
Frédéric Hamidi Avatar answered Jan 04 '23 23:01

Frédéric Hamidi


  • 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

like image 30
SLaks Avatar answered Jan 04 '23 23:01

SLaks