Every now and then I find myself needing to set multiple values to an enum object and test this later on, synonymously I usually find myself also scouring the net on the best practice on how to set, access and test these enum flags
So today I thought I would post a definitive reference I found on the net..
Specify flag-annotated enum:
[Flags]
public enum Column
{
None = 0,
Priority = 1 << 0,
Customer = 1 << 1,
Contract = 1 << 2,
Description = 1 << 3,
Tech = 1 << 4,
Created = 1 << 5,
Scheduled = 1 << 6,
DueDate = 1 << 7,
All = int.MaxValue
};
The [Flags] attribute allows you to do this:
Column MyColumns = Column.Customer | Column.Contract;
To check if contains flag:
if ((MyColumns & Column.Customer) != 0)
To check if has flag or higher:
if (MyColumns >= Column.Customer)
To check if has flag or lower:
if (MyColumns <= Column.Customer)
To set a flag:
MyColumns |= Column.Tech;
To clear a flag:
MyColumns &= ~Column.Tech;
To toggle (flip) a flag:
MyColumns ^= Column.Contract;
To clear all flags:
MyColumns = Column.None;
To set all flags:
MyColumns = Column.All;
To set all flags EXCEPT one or more:
MyColumns = Column.All ^ Column.Tech ^ Column.Status;
Credit to Jeremy Lundy for the comprehensive write up.
One Comment
Great article! Applies to many languages.
Post a Comment