Search code examples
c#enumsenum-flags

Couldn't understand Enum Flags with 0x2 values


I am trying to understand a portion of code but couldn't understand it so far ...

[Flags]
public enum Products
{
  Pepsi = 0x1,
  Coca = 0x2,
  Miranda = 0x3,
  Dew = 0x4,
  Wine = 0x5 
} 


Products pp = (Products)12;
pp.HasFlag(Products.Dew); ==> True
pp.HasFlag(Products.Miranda); ==> False
pp.HasFlag(Products.Coca); ==> False

I want to know why pp.HasFlag(Products.Dew) is True and pp.HasFlag(Products.Miranda) is False . I thought it is working as 0x1 = 1, 0x2 = 2, 0x3 = 4, 0x4 = 8, 0x5 = 16. Kindly guide me what is going on


Solution

  • Your initial declaration equals to

    [Flags]
    public enum Products
    {
      Pepsi = 0x1,
      Coca = 0x2,
      Miranda = Coca | Pepsi, // equals to 0x3 since 0x3 == 0x2 | 0x1
      Dew = 0x4,
      Wine = Dew | Pepsi      // equals to 0x5 since 0x5 == 0x4 | 0x1
    } 
    

    You probably want

    [Flags]
    public enum Products
    {
      Pepsi = 0x1,
      Coca = 0x2,
      Miranda = 0x4,
      Dew = 0x8,
      Wine = 0x10
    }