/ Published in: C#
Note the use of the Bitwise Complement Operator ( ~ ) to AND the negative of the bit you want to set.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
[Flags] private enum DeliveryOptions { //Make sure you start with zero and increment by powers of 2. //If you don't assign explicit values VS increments by 1. //Very bad. For example (One | Two = Three) None = 0, //(0000) Mail = 1, //(0001) Email = 2, //(0010) Fax = 4, //(0100) } private DeliveryOptions deliveryFlags; private void button2_Click(object sender, EventArgs e) { //Put some checkboxes on the form. //A [Flag] enum can hold multiple values at once. //Checking or unchecking boxes adds or removes values. MessageBox.Show(deliveryFlags.ToString()); MessageBox.Show(Convert.ToInt32(deliveryFlags).ToString()); } private bool CheckFlag(DeliveryOptions targetVal, DeliveryOptions checkVal) { return ((targetVal & checkVal) == checkVal); } private bool HasBeenEmailed(DeliveryOptions targetVal) { return CheckFlag(targetVal, DeliveryOptions.Email); } private void btnValueCheck_Click(object sender, EventArgs e) { bool emailDelivered = HasBeenEmailed(deliveryFlags) ; MessageBox.Show(emailDelivered.ToString()); } private void chkOne_CheckedChanged(object sender, EventArgs e) { { deliveryFlags |= DeliveryOptions.Mail; } else { deliveryFlags &= ~DeliveryOptions.Mail; } } private void chkTwo_CheckedChanged(object sender, EventArgs e) { { deliveryFlags |= DeliveryOptions.Email; } else { deliveryFlags &= ~DeliveryOptions.Email; } } private void chkThree_CheckedChanged(object sender, EventArgs e) { { deliveryFlags |= DeliveryOptions.Fax; } else { deliveryFlags &= ~DeliveryOptions.Fax; } }