Reputation: 103477
bool isValid = false;
string username = "someadmin";
If( !String.IsNullOrEmpty(username) && !( username.IndexOf("admin") != -1)
isValid = true;
The second part with the double negatives is crossing me up!
Upvotes: 0
Views: 926
Reputation: 54600
May I present to you DeMorgan's Laws:
NOT (P OR Q) = (NOT P) AND (NOT Q)
NOT (P AND Q) = (NOT P) OR (NOT Q)
So, you could rewrite it as:
if (!(String.IsNullOrEmpty(username) || username.IndexOf("admin") != -1)) {
isValid = true;
}
...thus removing the double negatives.
Furthermore, you could say:
if (String.IsNullOrEmpty(username) || username.IndexOf("admin") != -1) {
isValid = false;
}
...which removes all the negatives.
Also, you could say:
isValid = !(String.IsNullOrEmpty(username) || username.IndexOf("admin") != -1));
...to make it nice and compact.
Upvotes: 10
Reputation: 22773
It will give you a syntax error due to a missing paren ;-)
But seriously, it will return false.
!String.IsNullOrEmpty(username) // if username is NOT null and NOT empty => true
username.IndexOf("admin") != -1 // if "admin" IS FOUND in username (not -1) => true
!( username.IndexOf("admin") != -1 ) // if "admin" IS NOT FOUND in username => false
So, concluding: the conditions of the if statement are NOT met, so isValid will remain false.
PS.: I'm not a c# programmer, but I presume that when IndexOf(string) equals -1, it means not found.
Upvotes: 0
Reputation: 4595
false. But I don't get the question? Couldn't you just execute this? What double negatives? The value is just being inverted and the parentheses clearly indicate the order in which the statements are executed.
Upvotes: 0
Reputation: 13727
A plain language version:
if (username is not null or empty and username doesn't contain "admin") isValid = true;
Upvotes: 1
Reputation: 269278
isValid
will be false.
(Nitpick: this code doesn't "return" anything: it just sets the value of the isValid
variable.)
Upvotes: 0
Reputation: 17784
it will return false
!String.IsNullOrEmpty(username) // this is true, the string is not NullOrEmpty
!(username.IndexOf("admin") != -1) // IndexOf is >= 0, so != 1 is true. But the first ! makes it false
So IsValid will contain the same value as it had at the beginning...
Upvotes: 4