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


I have an enum which is defined like this:

public enum eRat { A = 0, B=3, C=5, D=8 };

So given value eRat.B, I want to get the next one which is eRat.C

The solution I see is (without range checking)

Array a = Enum.GetValues(typeof(eRat));
int i=0 ;
for (i = 0; i < a.GetLength(); i++)
       if (a.GetValue(i) == eRat.B)
return (eRat)a.GetValue(i+1):

Now that is too much complexity, for something that simple. Do you know any better solution?? Something like eRat.B+1 or Enum.Next(Erat.B)?


Best Solution

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().