none
Bit Operator OR in C# Enum RRS feed

  • Question

  • I wrote Below Code : 


     class Program
        {


            enum Days { Sun = 1, Mon = 2, Tue = 3, Wed =4, Thu = 5, Fri = 6, Sat =7, Extra = 8 };

                         

            static void Main()
            {
               Console.WriteLine((Days.Tue | Days.Mon).ToString());
               Console.WriteLine((Days.Sun | Days.Wed).ToString());

               Console.WriteLine((Days.Sun | Days.Sat).ToString());

               Console.WriteLine((Days.Mon | Days.Fri).ToString());

             }
    }


    Output 

    // Tue  --- Why not Thu ??

    // Thu

    // Sat  -- Why not Extra 

    // Extra 


    why bit Operator is not  adding number 3,7 (odd numbers)  with Enum ? 

    Friday, May 5, 2017 3:49 PM

All replies

  • The | operator does not perform addition; it ORs corresponding bits.

    Tue equals 0x03.  Mon equals 0x02.  0x03 | 0x02 evaluates to 0x03.

    Sun equals 0x01.  Wed equals 0x04.  The ORed value is 0x05.

    I doubt the code you showed produced the fourth output you claim.

    Friday, May 5, 2017 9:13 PM