Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Toggle Enum Values of an Enum Variable

0.00/5 (No votes)
19 Sep 2014 1  
Toggle between enum values of an enum variable

Introduction

This tip shows you how to toggle between enum values of an enum variable.

Background

Let's take an enum example:

 enum Day
        {
            Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
        }
        Day day = Day.Sunday;
        private void Toggle()
        { 
            //Now, if you want to toggle values of the enum variable day what would you do?
            //generally if of switch statement is used like this 
            if (day == Day.Sunday)
                day = Day.Monday;
            else if (day == Day.Monday)
                day = Day.Tuesday;
            else if (day == Day.Tuesday)
                day = Day.Wednesday;
            else if (day == Day.Wednesday)
                day = Day.Thursday;
            else if (day == Day.Thursday)
                day = Day.Friday;
            else if (day == Day.Friday)
                day = Day.Saturday;
            else if (day == Day.Saturday)
                day = Day.Sunday;}

This method is only feasible when enum has few members (7 in this case). There is an easy way and it can also be feasible when enum has more members than usual.

Using the Code

 private void Toggle<T>(ref  T obj)
        {
            List<string> types = Enum.GetNames(obj.GetType()).ToList();
            int index = types.IndexOf(obj.ToString());
            if (index == types.Count - 1)
                index = 0;
            else
                index++;
            string nextstring = types[index];
            Type type = obj.GetType();
            object selected = Enum.Parse(obj.GetType(), nextstring);
            obj = (T)selected;
        }
        //Example 
        private void ChangeEnumValue()
        {
            Toggle<Day>(ref day);
        }

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here