Reputation: 253
I saw How to get next (or previous) enum value in C# and was wondering if that could also return the first item if the next item would be (last+1). So imagine:
public enum MODE {
OFF,
CHANNEL,
TALKING
}
MODE Mode = MODE.OFF;
Mode = Mode.Next(); // should give me MODE.CHANNEL
Mode = Mode.Next(); // should give me MODE.TALKING
Mode = Mode.Next(); // should give me MODE.OFF
Upvotes: 1
Views: 1989
Reputation: 76
Maybe this could be useful:
static void Main(string[] args)
{
MODE Mode = MODE.TALKING; //Whatever value;
int index = (int)Mode;
index = ++index % 3;
Mode = (MODE)index;
Console.WriteLine("Mode value {0} ; index {1}", Mode, index );
Console.ReadKey();
}
Upvotes: 0
Reputation: 186698
Add modulo arithmetics to husayt's answer
How to get next (or previous) enum value in C#
Code:
public static class Extensions {
public static T Next<T>(this T src) where T : struct {
if (!typeof(T).IsEnum)
throw new ArgumentException(String.Format("Argument {0} is not an Enum",
typeof(T).FullName));
T[] Arr = (T[])Enum.GetValues(src.GetType());
int j = (Array.IndexOf<T>(Arr, src) + 1) % Arr.Length; // <- Modulo % Arr.Length added
return Arr[j];
}
}
Upvotes: 2