user6807975 - 1 year ago 57

C# Question

`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`

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`

`value`

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**