Monday 18 April 2011

Dot.Net: What are Enum Flags

Question:
What are Enum Flags?
What are Enums that work like Bit Flags?
How can an enum variable hold more than one (multiple) enum value?


Answer:
Enums that work like Bit Flags are simple enums that you annotate with the [Flags] attribute and set explicit values that are useful for binary combination.

Here is an example
[Flags]
public enum Seasons
{
    Spring = 1,
    Summer = 2,
    Autumn = 4,
    Winter = 8,
    MyFavorite = 5, // I like spring and autumn
    YourFavorite = 3 // You like spring and summer
}

  • All seasons are bitwise disjunct.
  • Some Enum choices like MyFavorite are combinations of basic Enums.
  • It is the bit flag property of these Enums that allows for combination.

Spring       = 1 => 0 0 0 1
Summer       = 2 => 0 0 1 0
Autumn       = 4 => 0 1 0 0
Winter       = 8 => 1 0 0 0
MyFavorit    = 5 => 0 1 0 1
YourFavorite = 3 => 0 0 1 1

Test if a enum bit flag contains one specific value (spring)
public bool IsSpringLike(Seasons season)
{
    // test if the season is spring or a combination that contains spring
    return ((season & Seasons.Spring) == Seasons.Spring);
}

Add a enum flag to another existing enum
public void CombineEnums(Seasons s1, Seasons s2)
{
    // Bitwise OR merges s2 into s1
    return s1 = s1 | s2;
}

Remove a enum flag from an existing enum
public void SubstractEnums(Seasons s1, Seasons s2)
{
    // Bitwise XOR substructs s2 from s1
    return s1 = s1 ^ s2;
}

No comments: