Monday, January 07, 2008

Enum Flags

The following code demostrates how to use enum type in c# as flags.

        [Flags]
        public enum  test
        {
            none = 0,
            a = 0x01,
            b = 0x02,
             c = 0x04,
            d = 0x08
        }
        static  void Main(string[] args)
        {
            test t =  test.none;
            Console.WriteLine(t);
 
            t = t |  test.a; //set bit a
            Console.WriteLine(t);
 
             if (t == test.a) 
                Console.WriteLine( "only bit a is set");
 
            t = t | test.b;  // set bit a
            Console.WriteLine(t);
 
             if ((t & test.a) != 0) //test to see if bit a is set
                 Console.WriteLine(" test bit a is set");
 
            Console .ReadKey();
        }

The implementation I was using is to use the BitArray which is very efficient. The good news is I implemented by using code generation which means I only need to modify the code generation templates and all my generated code will be benefiting. :)


No comments: