Why are people always using enum values like 0, 1, 2, 4, 8
and not 0, 1, 2, 3, 4
?
Has this something to do with bit operations, etc.?
I would really appreciate a small sample snippet on how this is used correctly :)
[Flags]
public enum Permissions
{
None = 0,
Read = 1,
Write = 2,
Delete = 4
}
These are used to represent bit flags which allows combinations of enum values. I think it's clearer if you write the values in hex notation
Because these values represent unique bit locations in binary:
etc., so
EDIT:
3 in binary is represented by a value of 1 in both the ones place and the twos place. It is actually the same as the value
1 | 2
. So when you are trying to use the binary places as flags to represent some state, 3 isn't usually meaningful (unless there is a logical value that actually is the combination of the two)For further clarification, you might want to extend your example enum as follows:
Therefore in I have
Permissions.All
, I also implicitly havePermissions.Read
,Permissions.Write
, andPermissions.Delete
If it is still not clear from the other answers, think about it like this:
is just a shorter way to write:
There are eight possibilities but you can represent them as combinations of only four members. If there were sixteen possibilities then you could represent them as combinations of only five members. If there were four billion possibilities then you could represent them as combinations of only 33 members! It is obviously far better to have only 33 members, each (except zero) a power of two, than to try to name four billion items in an enum.
Lot's of good answers to this one… I'll just say.. if you do not like, or cannot easily grasp what the
<<
syntax is trying to express.. I personally prefer an alternative (and dare I say, straightforward enum declaration style)…LOG 513 == 513
So much easier (for myself, at least) to comprehend. Line up the ones… describe the result you desire, get the result you WANT.. No "calculations" necessary.
Because they are powers of two and I can do this:
And perhaps later...
It is a bit field, where each set bit corresponds to some permission (or whatever the enumerated value logically corresponds to). If these were defined as
1, 2, 3, ...
you would not be able to use bitwise operators in this fashion and get meaningful results. To delve deeper...Notice a pattern here? Now if we take my original example, i.e.,
Then...
See? Both the
Read
andWrite
bits are set, and I can check that independently (Also notice that theDelete
bit is not set and therefore this value does not convey permission to delete).It allows one to store multiple flags in a single field of bits.
I think writing like this is easier to understand and read, and you don't need to calculate it.