Reputation:
I have this Or condition in an IF statement (in a foreach loop) in a Windows Form C# program:
if ((splittedFile.Count() != 3) || (splittedFile.Count() != 4))
continue;
and it always does continue
, even if splittedFile.Count()
is 3 or 4.
The thing is that if I remove the Or condition:
if ((splittedFile.Count() != 4))
continue;
it works properly!! Any ideas why?
Upvotes: 0
Views: 3577
Reputation: 98840
Because one of your expressions will be always true
. That's why true || something
always returns true
.
Let's analyze your splittedFile.Count()
is 3
, 4
and other than these values.
3
, your expression will be false || true
and this returns true
.4
, your expression will be true || false
and this returns true
.3
or 4
, your expression will be true || true
and this returns true
.Strongly suspect you are looking for &&
operator which provides logical-AND.
Upvotes: 1
Reputation: 477265
This is the correct behavior, you need to use &&
.
The reason is that the count is fixed number, let's say n. Now the condition reads:
n is not 3 or n is not 4.
Given n is 4, this means it is not 3, thus the test succeeds and vice versa.
A compiler can't detect this is trivially true, because between the two if
statements, the Count()
might change (for instance in a multithreading setting where the second thread would add/remove something to/from the collection). I agree however some analysis tools could be capable in some conditions to detect such trivial behavior. In general however such analysis can't be implemented because of Rice's theorem.
If you use &&
, the expression reads:
n is not 3 and n is not 4.
Thus both conditions should be true. In other words only if n is less than three and greater than 4, the condition holds.
Upvotes: 4
Reputation: 25370
put a real number into your expression:
if( 3 != 3 || 3 != 4)
which is
if( false || true )
your expression will always be true, as splittedFile.Count()
is always (not 3) or (not 4)
you want to &&
your results together, which looks like
(x != 3) || (x != 4)
or
!( x == 3 || x == 4)
Upvotes: 2
Reputation: 36503
Try:
if ((splittedFile.Count() != 3) && (splittedFile.Count() != 4))
continue;
I know ||
sound logical because : if splittedFile.count is not 3 OR it is not 4 then continue;
But because there are 2 NOT !
operators in the if expression an AND &&
is needed.
Upvotes: 3