Look at this code snippet:
Console
.WriteLine("9 > 7 is " + (9 > 7));All it does is print "9 > 7 is True." to the screen. The parentheses are necessary otherwise the compiler complains saying "Operator ' >' cannot be applied to operands string and int.
I'm trying to understand the compilers message. All I understand is that by putting parentheses around the (9 > 7) part you force the compiler to evaluate what's in them first. So if I remove the parentheses, what is the compiler trying to do when it says "Operator '>' cannot be applied to operands string and int?
Is it trying to perform a comparison between the string "9 > 7 is" and the > 7 or the 9 > 7 part?
Tim KangasPosted Aug 6, 2007, 5:37 PM
AlanPosted Aug 6, 2007, 3:41 PM
If you remove the parenthesis from (9 > 7), then the first operation the compiler does is:
"9 > 7 is " + 9
This results in the string "9 > 7 is 9". Let's call it 's'.
It then attempts this operation:
s > 7
However, this fails because the '>' operator is not defined when the first operand is a string and the second is an int.
The surprise here is that a strongly typed language such as C# permits the first operation which to me is very VB'ish. However, it does and so you occasionally get these rather strange compiler errors :)