1

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

Waqar Ahmed
  • 1,414
  • 2
  • 15
  • 35

4 Answers4

4

You're mistaken about 0x means. 0x5 does not equal 16, it equals 5. 0x lets you write hexadecimal, so that you could write 0xA = 10.

Change your definition to be:

public enum Products
{
    Pepsi = 1,
    Coca = 2,
    Miranda = 4,
    Dew = 8,
    Wine = 16 
} 

Thus, 12 would represent the flag Dew and Miranda

Rob
  • 26,989
  • 16
  • 82
  • 98
  • HasFlag(Products.Dew) is True ? – Waqar Ahmed Jan 20 '16 at 06:22
  • 2
    @WaqarAhmed Yes, because `12` represents `8+4` (which is Dew and Miranda). – Rob Jan 20 '16 at 06:23
  • According to my code Why pp.HasFlag(Products.Dew) is True and pp.HasFlag(Products.Miranda) is False? – Waqar Ahmed Jan 20 '16 at 06:25
  • 2
    @WaqarAhmed Because `12` is `1100` in binary. `Miranda (3)` is `0011`. `Dew (4)` is `0100`. `0100 & 1100` yields `0100`, so the flag is *on* for Dew. `0011 & 1100` yields `0000`, so the flag is *off* for miranda. – Rob Jan 20 '16 at 06:28
1

You should read this topic. Your flags are little bit incorrect. For example:

Pepsi | Cola = Miranda
 0001 | 0010 = 0011

Logically right flags:

[Flags]
public enum Products
{
  Pepsi = 0x1,
  Coca = 0x2,
  Miranda = 0x4,
  Dew = 0x8,
  Wine = 0x0A 
} 
Community
  • 1
  • 1
Andrey Burykin
  • 700
  • 11
  • 23
1

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
} 
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

In order to understand Flags it's better to convert each flag value to its binary representation. So in your case we have:

[Flags]
public enum Products
{
  Pepsi = 0x1, //--> 0001
  Coca = 0x2, //--> 0010
  Miranda = 0x3, //--> 0011
  Dew = 0x4, //--> 0100
  Wine = 0x5 // --> 0101
} 

then when 12 (which in binary is '1100') casted to Products enum you can clearly see that the flag bit for Dew (which is 0100) is on (or 1 in binary). In other words, every product which its third bit from right is 1 has Dew in it.

Arin Ghazarian
  • 5,105
  • 3
  • 23
  • 21