How to get next (or previous) enum value in C#

Thanks to everybody for your answers and feedback. I was surprised to get so many of them. Looking at them and using some of the ideas, I came up with this solution, which works best for me:

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;
        return (Arr.Length==j) ? Arr[0] : Arr[j];            
    }
}

The beauty of this approach, that it is simple and universal to use. Implemented as generic extension method, you can call it on any enum this way:

return eRat.B.Next();

Notice, I am using generalized extension method, thus I don’t need to specify type upon call, just .Next().

Leave a Comment