The left-shift operator (<<
) can be used in flag enum declarations to ensure that each flag has exactly one 1
in binary representation, as flags should.
This also helps to improve readability of large enums with plenty of flags in them.
[Flags]
public enum MyEnum
{
None = 0,
Flag1 = 1 << 0,
Flag2 = 1 << 1,
Flag3 = 1 << 2,
Flag4 = 1 << 3,
Flag5 = 1 << 4,
...
Flag31 = 1 << 30
}
It is obvious now that MyEnum
contains proper flags only and not any messy stuff like Flag30 = 1073741822
(or 111111111111111111111111111110 in binary) which is inappropriate.