H
Hrvoje Voda
How can I use in If statement Or?
for example. if (x>10 or y>10)
{
....
}
Hrcko
for example. if (x>10 or y>10)
{
....
}
Hrcko
Hrvoje Voda said:How can I use in If statement Or?
for example. if (x>10 or y>10)
Paul E Collins said:if (x > 10 || y > 10) // or
if (x > 10 && y > 10) // and
P.
Jako said:It might be worth mentioning short-circuiting for the conditional statements
above.
if (x > 10 | y > 10) will work fine in this case.
by using || it "short-circuits" the conditional, i.e. it will evaluate x >
10 and only if this is false, y > 10 will be evaluated.
Similarly in if(x > 10 && y > 10), x > 10 will be evaluated and only if tihs
is true, y > 10 will be evaluated.
In the case mentioned it won't make a difference, but be careful when doing
something like:
(1) if (++x > 10 || ++y > 10)
as opposed to
(2) if (++x > 10 | ++y > 10)
In (1) ++y will only be execute if ++x is greater than 10, but in (2) both
++x and ++y will be executed.
I don't to confuse the issue, but I do think it's important to keep this in
mind.
Paul said:if (x > 10 || y > 10) // or
if (x > 10 && y > 10) // and
P.
Bruce Wood said:I wouldn't say that the operators are useless. In fact, they're very
useful for doing bit manipulation. It's probably just an accident of
the language that they can also be used for constructing conditional
expressions that don't short-circuit.
The | and & operators are enormously useful for manipulating Enum types
that have the [Flags] attribute. I use them often for that purpose.
I wouldn't use them in a condition, though, because I could always code
the condition in a different way that wouldn't require it, and the
"different way," although it would be much more long-winded, would be
easier to understand.
In fact, I just thought of an example from my own code. In my WinForms
code I have a method that calls a method for each different control on
my form to validate the control's contents and display an error icon if
it's invalid. I want to call every single method, so that any controls
with bad contents will display an error handler icon next to them. So,
I could say:
return ValidateControl1() & ValidateControl2() & ValidateControl3();
However, how many programmers reading my code would notice that there
was only one &, not two, and so every method would always be called.
Instead, I coded this:
I agree, this would be most puzzling to the average debugger and issadhu said:What kind of convoluted logic is this? For avoiding an or, you are
calling two methods and two properties??
Regards
Senthil
sadhu said:What kind of convoluted logic is this? For avoiding an or, you are
calling two methods and two properties??
Regards
Senthil
Fair enough, I can see where you're coming from. So we agree that & and |
as conditional operators are parts of C# that they could've left out.
I'm just happy for having && and || in C#, because in my VB6 days it used to
drive me insane to have to code the way you showed below!