Click here to Skip to main content
15,918,889 members
Articles / Programming Languages / C#
Tip/Trick

Toggle Enum Values of an Enum Variable

Rate me:
Please Sign up or sign in to vote.
4.67/5 (5 votes)
19 Sep 2014CPOL 18.4K   9   4
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:

C#
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

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Student
Nepal Nepal
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionMinor simplification of the code Pin
djmarcus22-Sep-14 7:26
djmarcus22-Sep-14 7:26 
GeneralRe: Minor simplification of the code Pin
PIEBALDconsult22-Sep-14 8:21
mvePIEBALDconsult22-Sep-14 8:21 
SuggestionMuch simpler method to do the same thing... Pin
Yogesh Jagota19-Sep-14 9:20
Yogesh Jagota19-Sep-14 9:20 
GeneralThoughts Pin
PIEBALDconsult19-Sep-14 5:54
mvePIEBALDconsult19-Sep-14 5:54 
"Toggle" usually implies switching between two values. "Increment" might be a more accurate word to use for this code.


void Toggle<T>(ref T obj)

I don't think you gain anything by using ref; you should simply return the new value.


I recommend you test the type T to ensure that it is an enum rather than allow the code to blow up with a meaningless Exception. Far better to throw an Exception that explicitly states the cause of the problem.


Use typeof(T) to get the type and its members. In fact I see three calls to obj.GetType() when one will do.
Type type = obj.GetType(); You don't seem to even use the variable; move it to the top and use it.
This is even better if you make a generic class and cache the information for repeated use rather than getting the same static information again and again on each call.



if (index == types.Count - 1)<br />
                index = 0;<br />
            else<br />
                index++;<br />


Try index = ( index + 1 ) % types.Count


Consider the following:

C#
public static class EnumTools<T>
{
    private static readonly System.Type type ;
    private static readonly System.Collections.Generic.List<string> types ;

    static EnumTools
    (
    )
    {
        type = typeof(T) ;

        if ( !type.IsEnum ) throw new System.ArgumentException ( "The generic type T must be an enumeration" , "T" ) ;

        types = new System.Collections.Generic.List<string> ( System.Enum.GetNames(type));
    }

    public static T Toggle( T obj)
    {
        return ( (T)System.Enum.Parse(type, types[(types.IndexOf(obj.ToString()) + 1 ) % types.Count ]) );
    }
}



Also note that it doesn't work with enumerations like:

C#
public enum E
{
    Foo = 42
,
    Bar = 42
}


modified 19-Sep-14 19:02pm.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.