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

1
  • I don't really see a reason to downvote this question. At least not whithout stating a reason... Commented Jan 20, 2016 at 6:27

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

4 Comments

HasFlag(Products.Dew) is True ?
@WaqarAhmed Yes, because 12 represents 8+4 (which is Dew and Miranda).
According to my code Why pp.HasFlag(Products.Dew) is True and pp.HasFlag(Products.Miranda) is False?
@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.
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 } 

Comments

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 } 

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.