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
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.
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.
CA1069: Enums should not have duplicate values.
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 .
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With