FlagsAttribute [Flags]

Just used this for something I’m working on and thought I better write the details down due to a slight oddity I found while using it.

Note that the important point that you need to remember is that you must start the numbering at 1… not 0(zero)!!!

Take a flags enum like this:

[Flags]
public enum MyFlagsEnum
{
    Archived = 1,
    Closed = 2,
    Open = 4
}

The important thing about the above is that I’ve specified the values and started at one(1) Don’t start with zero(0)

Another way to do this (especially if you’ve got a fair few items:

[Flags]
public enum MyFlagsEnum
{
    Archived = 1,
    Closed = 1 << 1,
    Open = 1 << 2
}

Which generated the same enumeration with the same values.

If you want to combine values into another option, you can do this…

[Flags]
public enum MyFlagsEnum
{
    Archived = 1,
    Closed = 1 << 1,
    Open = 1 << 2,
    All = Archived | Closed | Open
}

The following unit test shows assigning of a new variable of type MyFlagsEnum and assigns the Open and Archived option…

[TestMethod]
public void OpenAndArchived()
{
    MyFlagsEnum options = MyFlagsEnum.Open | MyFlagsEnum.Archived;

    Assert.IsTrue((options & MyFlagsEnum.Open) == MyFlagsEnum.Open);
    Assert.IsFalse((options & MyFlagsEnum.Closed) == MyFlagsEnum.Closed);
    Assert.IsTrue((options & MyFlagsEnum.Archived) == MyFlagsEnum.Archived);
}

As you can see you do this by ORing the flags together

MyFlagsEnum options = MyFlagsEnum.Open | MyFlagsEnum.Archived;

To test whether the  options variable has the Open flag you AND the option against the type that you want to check the variable contains (for lack of a better word!) This anding should return either zero(0) which is why you don’t want to include an enum with a value of zero(0), or will return just the value you are looking for (The ANDing essentially returns a MyFlagsEnum(in this case) which doesn’t includes the value of only the item that you ANDed the variable with)

Assert.IsTrue((options & MyFlagsEnum.Open) == MyFlagsEnum.Open);

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: