Explain me a code example please | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Explain me a code example please

This is code from https://docs.microsoft.com/ru-ru/dotnet/csharp/programming-guide/enumeration-types So there is written that "Days has the Flags attribute, and each value is assigned the next greater power of 2" but in code they don't use numbers of power of 2. I had teasted it and the code doesn't work with numbers of power of 2. So, what is that numbers is? Why is it working? Code here class Program { [Flags] enum Days { None = 0x0, Sunday = 0x1, Monday = 0x2, Tuesday = 0x4, Wednesday = 0x8, Thursday = 0x10, Friday = 0x20, Saturday = 0x40 } static void Main(string[] args) { Days meetingDays = Days.Tuesday | Days.Thursday; // Initialize with two flags using bitwise OR. meetingDays = Days.Tuesday | Days.Thursday; // Set an additional flag using bitwise OR. meetingDays = meetingDays | Days.Friday; Console.WriteLine("Meeting days are {0}", meetingDays); // Output: Meeting days are Tuesday, Thursday, Friday // Remove a flag using bitwise XOR. meetingDays = meetingDays ^ Days.Tuesday; Console.WriteLine("Meeting days are {0}", meetingDays); // Output: Meeting days are Thursday, Friday // Test value of flags using bitwise AND. bool test = (meetingDays & Days.Thursday) == Days.Thursday; Console.WriteLine("Thursday {0} a meeting day.", test == true ? "is" : "is not"); // Output: Thursday is a meeting day. } }

29th Aug 2018, 9:11 AM
Evgenii Shiliaev
Evgenii Shiliaev - avatar
1 Answer
+ 1
Because [Flags] means that the enum is really a bitfield. With [Flags] you can use the bitwise AND (&) and OR (|) operators to combine the flags. When dealing with binary values like this, it is almost always more clear to use hexadecimal values. 0x means that it is hexadecimal value. https://stackoverflow.com/questions/13222671/why-are-flag-enums-usually-defined-with-hexadecimal-values The example is working fine. https://code.sololearn.com/cG71IT3AULLb
29th Aug 2018, 11:25 AM
sneeze
sneeze - avatar