Monday, January 07, 2008

Enum Flags

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

        public enum  test
            none = 0,
            a = 0x01,
            b = 0x02,
             c = 0x04,
            d = 0x08
        static  void Main(string[] args)
            test t =  test.none;
            t = t |  test.a; //set bit a
             if (t == test.a) 
                Console.WriteLine( "only bit a is set");
            t = t | test.b;  // set bit a
             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: