Using a Flag Enumeration with Bitwise Operations


/ Published in: C#
Save to your folder(s)

Note the use of the Bitwise Complement Operator ( ~ ) to AND the negative of the bit you want to set.


Copy this code and paste it in your HTML
  1. [Flags]
  2. private enum DeliveryOptions
  3. {
  4. //Make sure you start with zero and increment by powers of 2.
  5. //If you don't assign explicit values VS increments by 1.
  6. //Very bad. For example (One | Two = Three)
  7. None = 0, //(0000)
  8. Mail = 1, //(0001)
  9. Email = 2, //(0010)
  10. Fax = 4, //(0100)
  11. }
  12.  
  13. private DeliveryOptions deliveryFlags;
  14.  
  15. private void button2_Click(object sender, EventArgs e)
  16. {
  17. //Put some checkboxes on the form.
  18. //A [Flag] enum can hold multiple values at once.
  19. //Checking or unchecking boxes adds or removes values.
  20. MessageBox.Show(deliveryFlags.ToString());
  21. MessageBox.Show(Convert.ToInt32(deliveryFlags).ToString());
  22. }
  23.  
  24. private bool CheckFlag(DeliveryOptions targetVal, DeliveryOptions checkVal)
  25. {
  26. return ((targetVal & checkVal) == checkVal);
  27. }
  28. private bool HasBeenEmailed(DeliveryOptions targetVal)
  29. {
  30. return CheckFlag(targetVal, DeliveryOptions.Email);
  31. }
  32.  
  33. private void btnValueCheck_Click(object sender, EventArgs e)
  34. {
  35. bool emailDelivered = HasBeenEmailed(deliveryFlags) ;
  36. MessageBox.Show(emailDelivered.ToString());
  37. }
  38.  
  39. private void chkOne_CheckedChanged(object sender, EventArgs e)
  40. {
  41. if (chkMail.Checked)
  42. {
  43. deliveryFlags |= DeliveryOptions.Mail;
  44. }
  45. else
  46. {
  47. deliveryFlags &= ~DeliveryOptions.Mail;
  48. }
  49. }
  50.  
  51. private void chkTwo_CheckedChanged(object sender, EventArgs e)
  52. {
  53. if (chkEmail.Checked)
  54. {
  55. deliveryFlags |= DeliveryOptions.Email;
  56. }
  57. else
  58. {
  59. deliveryFlags &= ~DeliveryOptions.Email;
  60. }
  61. }
  62.  
  63. private void chkThree_CheckedChanged(object sender, EventArgs e)
  64. {
  65. if (chkFax.Checked)
  66. {
  67. deliveryFlags |= DeliveryOptions.Fax;
  68. }
  69. else
  70. {
  71. deliveryFlags &= ~DeliveryOptions.Fax;
  72. }
  73. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.