![]() |
Need a little clarification
Look at this line of code:
:
Console.WriteLine("9 > 7 is " + (9 > 7));All it does is print "9 > 7 is True. The parentheses are needed because without them the compiler says this to me: Operator '>' cannot be applied to operands of type string and int. According to Herb, he says the parentheses are needed because the + operator has a higher precedence than the > operator. I'm trying to understand the compilers message. I understand what Herb is saying. By putting parentheses around the (9 > 7) you force the compiler to evaluate those right away. I guess I don't quite understand what the compiler's message is though. When I omit the parentheses, what does the compiler "think" I'm trying to do? |
It thinks you are trying to write something to the console. Hence when you type Console.WriteLine. Your problem is that WriteLine only takes 1 parameter (as far as I know anyways). The first parameter anyways is a string. The error you're getting is telling you that you can't compare a string and an int using the '>' operator. You can put anything you want between the brackets for the parameter, but in the end, for it to work, it has to be a valid string. The reason it works with the code you provided is that, you had text and applied the + operator, meaning to add on to the string in this case, and you provided (9 > 7). It evaluates the equation in parentheses and connects it to the string.
To tell you the truth I'm a little surprised it works with the code you provided. I would have thought that when it evaluated (9 > 7), it would return true, but would throw you a similar error telling you you can't convert a bool to string. |
So without the parentheses is the compiler kind of seeing this whole thing as a string:
:
9 > 7 is + 9I see the + 9 part as concatenating an integer onto the end of a string, but maybe the compiler sees it as concatenating a string(the character 9)onto the string "9 > 7". |
Quote:
Quote:
|
Aha, that explains it. Thanks.
|
So without the parentheses around the (9 > 7) part, the compiler attempts to compare the string "9 > 7 is" with the > 7 or the 9 > 7 part? And because you can't compare a string to an int the compiler says "error".
|
Order of operations;)
|
:
"9 > 7 is " + 9 > 7is the same as :
("9 > 7 is " + 9) > 7if that makes it more clear. |
Yes that helps. I kind of suspected that.
|
| All times are GMT -5. The time now is 3:07 AM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC