// Scott Sibley using System; class FlagsAndBits { [Flags] // FlagsAttribute - Deal with the the enum as a flags list public enum MyBits { // The enum represents binary numbers, so we can turn bits // on and off. i.e. if we don't want brave, but we want all // other flags, the binary number would be (from right to left) // 1110 -- contrived by or'ing the relevant flags // ---- // 0010 -- smart // 0100 -- charming // 1000 -- happy // // A test to see if brave exists // 1110 // 0001 (and the numbers, no matches) // 0000 // = Does not exist // // Test to see if smart exists // 1110 // 0010 (and the numbers, matches) // 0010 // = Exists brave = 1, // 2^0 smart = 2, // 2^1 charming = 4, // 2^2 happy = 8 // 2^3 } static void Main() { MyBits bits = MyBits.brave | MyBits.charming; // Set these two bits // Shows a comma seperated list of flags. The FlagsAttribute causes this // behaviour. Otherwise, the numeric value would be shown instead. Console.WriteLine( bits.ToString() ); Console.WriteLine( bits & MyBits.happy ); // Does the happy flag exist? Console.WriteLine( bits & MyBits.smart ); // Does the smart flag exist? Console.WriteLine(); // Build a set of flags via a comma seperated list MyBits moreBits = (MyBits)Enum.Parse( typeof(MyBits), "charming,happy", true); // Show the value of moreBits. It is comma seperated. Console.WriteLine( moreBits.ToString() ); // This FlagsAttribute enum can be cast as an integer. Prints the numeric value. Console.WriteLine( (int)moreBits ); } }