Operator '==' cannot be applied to operands of type 'int' and 'string

You ask for a number, but you are trying to compare it to non-numeric data. Forget language semantics, how do you expect to compare a number to text? What does it mean to ask if a number like 3 is equal to “higher”?

The answer is that it is nonsensical; this is one reason why the language does not allow it.

int a = 1;
string b = "hello";

if (a == 1)       { /* This works; comparing an int to an int */ }
if (a == "hello") { /* Comparing an int to a string!? This does not work. */ }
if (b == 1)       { /* Also does not work -- comparing a string to an int. */ }
if (b == "hello") { /* Works -- comparing a string to a string. */ }

You can force the comparison to compile by converting your number to a string:

if (answer.ToString() == "higher")

But this condition will never be met because there is no int value that would convert to the text “hello”. Any code inside of the if block would be guaranteed never to execute. You might as well write if (false).

Browse More Popular Posts

Leave a Comment