- Home /
the 'or' operator not working? C#
Hi Guys/Girls,
I'm trying to write a simple if statement with an 'or' in it but can't get it working? What have i done wrong?
if(myVariable == 15||30||45){
//do something
}
myVariable is an int so i thought it would just work?
Cheers
Answer by kdubnz · Dec 01, 2014 at 06:07 AM
Try something like :
if(myVariable == 15 ||
myVariable == 30 ||
myVariable == 45 )
{
//do something
}
And as an explanation, when you do something like myVariable == 15||30||45 then the C# compiler places brackets by the precedence rules like so
(myVariable) == (15||30||45)
the problem is that when you do 15||30||45 you might get compilation error or an undesired result cause 15 || 30 is not a well defined operation for compilers
@Helical, Actually, it's a little simpler than that. http://msdn.microsoft.com/en-us/library/6373h346.aspx
The conditional-OR operator (||) performs a logical-OR of its bool operands. If the first operand evaluates to true, the second operand isn't evaluated. If the first operand evaluates to false, the second operator deter$$anonymous$$es whether the OR expression as a whole evaluates to true or false.
So you should get an error something like
Operator '||' cannot be applied to operands of type 'int' and 'int'
Added:
I know the rules of Oring, i was trying hard to simplify my wording for those who don't program in their sleep.
@Hoorza - I can't imagine how that could be undesired behaviour? By definition, as soon as one TRUE condition is found, the result of the OR must be TRUE so the test can return straight away (i.e. "shortcut") without needlessly evaluating all the remaining conditions, which couldn't possibly alter the result.