Although I grasp the concept of Bitwise Operators, I can\'t say that I have come across many use cases during the webdevelopment process at which I had to resort to using Bi
This question is already answered but I would like to share my experience with &
.
I have used &
a short time ago to validate a signup form when I was doing an ASP.NET C# exercise where the short-circuited &&
would not achieve a desired effect as easily.
What I wanted to do was highlight all invalid fields in the form and show an error message label right beside each invalid field, and dehighlight all valid fields and remove the error messages from them.
The code I used it was something like this:
protected void btnSubmitClicked(...) {
username = txtUsername.Text;
email = txtEmail.Text;
pass = txtPassword.Text;
if (isUsernameValid(username) & isEmailValid(email) & isPasswordValid(pass)) {
// form is valid
} else {
// form is invalid
}
...
}
private bool isPasswordValid(string password) {
bool valid = true;
string msg = "";
if (password.length < MIN_PASSWORD_SIZE) {
valid = false;
msg = "Password must be at least " + MIN_PASSWORD_SIZE + " long.";
}
highlightField(txtPassword, lblPassword, valid, msg);
return valid;
}
private void highlightField(WebControl field, Label label, string valid, string msg) {
if (isValid) {
// de-highlight
field.BorderColor = VALID_FIELD_COLOR;
} else {
// highlight the text field and focus on it
field.BorderColor = INVALID_FIELD_COLOR;
field.Focus();
}
label.Text = msg;
}
// and other similar functions for username and email
Were I to use &&
instead of &
, the if-statement in btnSubmitClicked
method would highlight only the very first invalid field, and all the other invalid fields after that would not be highlighted and its error message not shown because short-circuited &&
would stop checking the condition after a false is encountered.
There may be a better way to achieve the same thing, but I found &
useful at that time.