Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

enums

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)             break; } 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)?

Thanks

like image 585
husayt Avatar asked Mar 13 '09 12:03

husayt


People also ask

Is new enum value a breaking change?

In general, assume yes - it is a breaking change! It still could be a breaking change even if you are the only consumer. If anywhere in your code you cast between the int value to get the enum value, this could result in exceptions or (worse) the wrong value being returned.

Can enum values be compared in C?

How to compare Enum values in C#? Enum. CompareTo(Object) Method is used to compare the current instance to a specified object and returns an indication of their relative values.

Can enum have duplicate values?

CA1069: Enums should not have duplicate values.

Do enums have to be sequential?

It is not necessary to assign sequential values to Enum members. They can have any values. In the above example, we declared an enum PrintMedia .


1 Answers

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

like image 181
husayt Avatar answered Oct 14 '22 12:10

husayt