Why the values of enums are bit flag in .Net?

Take a look at AttributeTargets in System namespace:

  1. namespace System
  2. {
  3.     [Serializable]
  4.     [ComVisible(true)]
  5.     [Flags]
  6.     public enum AttributeTargets
  7.     {
  8.              Assembly = 1,
  9.              Module = 2,
  10.              Class = 4,
  11.              Struct = 8,
  12.              Enum = 16,
  13.              Constructor = 32,
  14.              Method = 64,
  15.             Property = 128,
  16.             Field = 256,
  17.             Event = 512,
  18.             Interface = 1024,
  19.             Parameter = 2048,
  20.             Delegate = 4096,
  21.             ReturnValue = 8192,
  22.             GenericParameter = 16384,
  23.             All = 32767,
  24.     }
  25. }

Have ever thinks about that why these values assigned to 1, 2, 4, 8, 16 , … ?? If you remember bit flag pattern, numbers look like this:

  1. 00000000  0
  2. 00000001  1
  3. 00000010  2
  4. 00000100  4
  5. 00001000  16
  6. 00010000  32
  7. 00100000  64
  8. 01000000  128

So, what's the benefit of this? They use these number to avoid combination of enum members specially when using bitwise operation! Imagine that you have written your  own enum like this:

  1.     public enum AccountState
  2.     {
  3.         Closed,
  4.         Blocked,
  5.         Active,
  6.         Forbidden
  7.     }

By default, enum will create the integer numbers: 0,1,2,3,4,5,6,…  now when you want to use this attribute somewhere like this:

  1.     Public class BitwiseClass
  2.     {
  3.         public void Method()
  4.         {
  5.             Account account = new Account();
  6.  
  7.             account.AccountState = AccountState.Active | AccountState.Blocked | AccountState.Forbidden |
  8.                                    AccountState.Forbidden;
  9.         }
  10.     }
  11.  
  12.     public class Account
  13.     {
  14.        public AccountState AccountState { get; set; }
  15.     }

 

In Method(), when you want to do bitwise operation, the combination of 1 and 2 is 3 , 0 and 1 is 1, 0 and 2 is 2 ,… So in this case system will combine these numbers! But in bit flag operation, numbers will look like this:

  1.    public enum AccountState
  2.     {
  3.         Closed,          // 0000
  4.         Blocked,       //  0001
  5.         Active,          //  0010
  6.         Forbidden   //   0100
  7.     }

The combination of these number never will be iterated. By the you don't need to assign these numbers in every enum! You just need to use Flags attribute:

  1.     [Flags]
  2.     public enum AccountState
  3.     {
  4.         Closed,
  5.         Blocked,
  6.         Active,
  7.         Forbidden
  8.     }


Tags: C#


comments powered by Disqus