How does Bit wise operators work with Enums

enum WeekDays
{
    Monday = 0,
    Tuesday = 1,
    Wednesday = 2,
    Thursday = 3,
    Friday = 4,
    Saturday = 5,
    Sunday = 6
}

private void button4_Click(object sender, EventArgs e)
{
    WeekDays days0 = WeekDays.Monday | WeekDays.Tuesday | WeekDays.Wednesday;

    WeekDays days1 = WeekDays.Monday | WeekDays.Tuesday | WeekDays.Wednesday | WeekDays.Thursday;

    WeekDays days2 = WeekDays.Monday | WeekDays.Tuesday | WeekDays.Wednesday | WeekDays.Thursday | WeekDays.Friday;
}

Output is:

days0 = Thursday,
days1 = Thursday,
days2 = 7

Can anybody explain the logic how this works?

Jon Skeet
people
quotationmark

Basically, your enum isn't suitable for use with bitwise operations. To be appropriate for bitwise operations, each distinct value should be represented by a different bit - whereas you've just got the numbers 0-6.

The reason you're getting the output you have is that:

  • days0 is 0 | 1 | 2, which is 3, the value of Thursday
  • days1 is 0 | 1 | 2 | 3 which is still 3, the value of Thursday
  • days2 is 0 | 1 | 2 | 3 | 4 which is 7, which isn't a named value in your enum

To make your enum work appropriate for bitwise operations, you should declare it like this:

[Flags] // Affects string parsing and formatting
enum BitwiseWeekDays
{
    None = 0,
    Monday = 1 << 0,
    Tuesday = 1 << 1,
    Wednesday = 1 << 2,
    Thursday = 1 << 3,
    Friday = 1 << 4,
    Saturday = 1 << 5,
    Sunday = 1 << 6
}

Now each value is represented by a separate bit, so you can "or" them together to combine them.

people

See more on this question at Stackoverflow