I love creating helpers, especially the most used ones. I recently wanted to find the next element of an enum. I created the following static method in a static class:
public static T GetNextEnumValue<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; return (Arr.Length == j) ? Arr[0] : Arr[j]; }
It simply takes one element of an enum it returns the next one. Similarly, you can find the previous element with a little change in the above method:
public static T GetPreviousEnumValue<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; return (Arr.Length == j) ? Arr[0] : Arr[j]; }
Cheers!