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
}
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
ReadandWritebits are set, and I can check that independently (Also notice that theDeletebit 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.