I am a bit confused by this. I want to hide a button if the current username of the system is !=
Administrator OR Administrator2, but the only way to get my desired goal is by using the &&
instead of ||
.
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
if
(userName != @"PC\Administrator" && userName != @"PC\Administrator2")
{
button2.Hide();
}
However, in another spot in my form to open button2
, if I use ==
it then seems to work?
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
var adminform = new AdminForm();
if (userName == @"PC\Administrator" || userName == @"PC\Administrator2")
{
adminform.Show();
}
Any idea why I can't use ||
when using !=
in the first example?
De Morgan's Laws for Boolean operations are an important skill for a programmer to understand intimately.
In your case, when negating you need additional parentheses to correctly order the operations, or as in your case change the ||
to an &&
. To use the ||
you'd put
if (!(userName == @"PC\Administrator" || userName == @"PC\Administrator2"))
Enclose the entire not expression in parenthesis and negate that. Like this:
if (!(userName == @"PC\Administrator" || userName == @"PC\Administrator2"))
{
button2.Hide();
}
It's the basic law of logic.
!(a && b) = !a || !b
Sometimes it's easier to write it in plain words to understand:
if username
is not equal to administrator
OR username
is not equal to administrator2
then hide the admin form
let's say that username
is administrator
Then the control will hide , because one of things is true (it's not administrator2
)
Why ?
question _____________________________________value
if username
is not equal to administrator
_________0
if username
is not equal to administrator2
________1
Ok, so the result is 0 or 1
which is true
First of all, I dont really have experience with c#, but if I understood your problem correctly it is the logic you use and not ac#-only thing.
You want the method "hide" to be called when the user is not one of the two administrators, but the logic you tried was to get two boolean values: user_is_not_admin1 user_in_not_admin2
When you use && you check that the user is not admin1 and not admin 2, which works as intended. But when replacing it with || you would check that the user is never both admin1 and admin2 at the same time (which seems strange if it were to happen). Instead, when attempting to use || you also need to move the nagation. What you want is to check that the user "is not (admin1 or admin2).
For further reading, take a look at De Morgans Law. http://en.wikipedia.org/wiki/De_Morgan%27s_laws
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.