The life of a code monkey

Text

Toggle an enum

Recently I have run into the problem where I created an enum to keep track of two states within my object. Sure  could have just used a boolean but the enum seemed to make the code easier to read.

        private enum SomeEnum : byte
        {
            FirstValue = 0,
            SecondValue = 1
        }

        private SomeEnum _value;

        public void ToggleValue()
        {
            _value ^= (SomeEnum)1;
            //Alternatively
            //_value = (SomeEnum)(((int)_value + 1) % 2);
        }
Posted on Tuesday, January 4 2011. Tagged with: C SharpEnumBit-wise Operators
1
Notes
  1. dotnetgeek posted this
Got a question or comment? Ask me.
Previous Next