user6807975 user6807975 - 1 month ago 7
C# Question

Why code enters if when the condition is not met?

enter image description here
Here is the code as text:

foreach (object value in values) {
if (value.ToString() != "HorizontalSlider" || value.ToString() != "EnterFieldSlider") {
// This code shouldn't be executing, but it is
if (value.ToString() == "Captcha") // ...


Why does this code enter the
if
statement when it's clearly not supposed to? I checked for typos and I didn't find any.


I'm using VS2015 and the project is based on .NET Framework 3.5

What might be worth adding: when the debugger stops on the first
if
statement seen in the image above, the preview of what
value
holds is not available.

Answer

Other people have pointed this out, but this shouldn't use an Or statement.

A helpful way to evaluate "if" statements is to consider what its negation is (i.e. when it's false - when it won't enter the "if" block). Let's represent what you have as

~A \/ ~B

(i.e. "not A or not B" - \/ just means "or" and ~ means "not").

The negation of this is:

~(~A \/ ~B).

According to DeMorgan's Laws,

~(A \/ B) <-> ~A /\ ~B
~(A /\ B) <-> ~A \/ ~B

Recall that /\ means "and", -> means "implies," and <-> means "these statements imply each other" (i.e. they're exactly equivalent).

To summarize these rules: the negation of "or" is "none of the above." The negation of "and" is "at least one of these." A double negative (i.e. ~~A) can be eliminated (i.e. ~~A <-> A).

Thus,

~(~A \/ ~B) -> ~~A /\ ~~B -> A /\ B

In other words, the only possible way that your "if" statement is false is if "value" equals both HorizontalSlider and "EnterFieldSlider." Since that will presumably never be the case, it will always be the case.

As others have indicated, replace || with &&. Again using DeMorgan's Laws:

~(~A /\ ~B) -> ~~A \/ ~~B -> A \/ B.

In other words, this is false (i.e. it does not enter the loop) when "value" is either HorizontalSlider or EnterFieldSlider.

Comments