71

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

2
  • this up to you. But let's say A, so we don't have to raise an exception.
    – husayt
    Commented Mar 13, 2009 at 16:00
  • @husayt: Code is updated. Now when you pass "D", "A" will be returned.
    – dance2die
    Commented Mar 13, 2009 at 19:57

26 Answers 26

108

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

3
  • 1
    Mostly worked for me. Type.IsEnum apparently doesn't exist for struct on Windows Phone Silverlight 8.0. Removed the type check and it works just fine.
    – azarc3
    Commented Nov 17, 2014 at 0:13
  • 9
    Why use struct when you can use where T : Enum ?
    – Vencovsky
    Commented Dec 7, 2020 at 19:34
  • Your answer does not seem to answer your question. It is missing the "previous"-part of your question.
    – Jogge
    Commented Feb 24, 2022 at 9:57
37

Probably a bit overkill, but:

eRat value = eRat.B;
eRat nextValue = Enum.GetValues(typeof(eRat)).Cast<eRat>()
        .SkipWhile(e => e != value).Skip(1).First();

or if you want the first that is numerically bigger:

eRat nextValue = Enum.GetValues(typeof(eRat)).Cast<eRat>()
        .First(e => (int)e > (int)value);

or for the next bigger numerically (doing the sort ourselves):

eRat nextValue = Enum.GetValues(typeof(eRat)).Cast<eRat>()
        .Where(e => (int)e > (int)value).OrderBy(e => e).First();

Hey, with LINQ as your hammer, the world is full of nails ;-p

7
  • 20
    +1 "with LINQ as your hammer" -> isn't hurting ourselves is the fastest way to learn? ;)
    – dance2die
    Commented Mar 13, 2009 at 13:46
  • 1
    Hey, I know I'm necromancing ;-) but speaking of hammers, be careful in high-performance situations with constructs like this (LINQ). Each LINQ statement ends up allocating a list internally. Thinking it cool, I used this kind of syntax in a very large project, and it quickly became the #1 hotspot of allocations. So sometimes, ugly but clean trumps hip & cool. Commented Feb 22, 2013 at 18:32
  • 1
    @KeithBluestone no, it is not correct to say that each LINQ operation allocates a list; most are done by iterator blocks. The main ones that need to buffer are OrderBy and GroupBy. Commented Feb 22, 2013 at 20:11
  • 1
    @MarcGravell Point taken, thanks. Overall I just wanted devs to be aware that under the friendly, semantically cozy hood of LINQ can lurk a lot of List<> allocations. I am a LINQ fan, and most of the time, it's not a problem; but writing some high-traffic code, it bit me. Commented Feb 23, 2013 at 1:06
  • This doesn't work when eRat value = eRat.D "InvalidOperationException Sequence contains no elements" rextester.com/live/YRGPO87367 Commented Oct 24, 2013 at 3:01
16

Do you really need to generalize this problem? Can you just do this instead?

public void SomeMethod(MyEnum myEnum)
{
    MyEnum? nextMyEnum = myEnum.Next();

    if (nextMyEnum.HasValue)
    {
        ...
    }
}

public static MyEnum? Next(this MyEnum myEnum)
{
    switch (myEnum)
    {
        case MyEnum.A:
            return MyEnum.B;
        case MyEnum.B:
            return MyEnum.C;
        case MyEnum.C:
            return MyEnum.D;
        default:
            return null;
    }
}
4
  • 3
    +1 simplicity. build something that solves the immediate need and move on. refactor later if necessary.
    – Rex M
    Commented Mar 13, 2009 at 13:42
  • 2
    Would it help if we assume that this IS the subsequent refactoring?
    – Whatsit
    Commented Mar 13, 2009 at 19:55
  • 49
    -1. I don't like this as it's a maintenance bug waiting to happen. The day you add something and you wonder why your code is returning null is a bad day indeed. Commented Mar 13, 2014 at 3:20
  • 1
    What @EddieParker said. With this solution you might have to remember that this code exist when you change the enum. On the long term it's easier and safer to generalize this so you can forget about it safely and don't have to look into this when you get an error you didn't expected. Commented Aug 12, 2022 at 8:02
12

The problem you're dealing with is because you're trying to get an enum to do something it shouldn't. They're supposed to be type safe. Assigning integral values to an enum is allowed so that you can combine them, but if you want them to represent integral values, use classes or structs. Here's a possible alternative:

public static class eRat
{
    public static readonly eRatValue A;
    public static readonly eRatValue B;
    public static readonly eRatValue C;
    public static readonly eRatValue D;

    static eRat()
    {
        D = new eRatValue(8, null);
        C = new eRatValue(5, D);
        B = new eRatValue(3, C);
        A = new eRatValue(0, B);
    }

    #region Nested type: ERatValue
    public class eRatValue
    {
        private readonly eRatValue next;
        private readonly int value;

        public eRatValue(int value, eRatValue next)
        {
            this.value = value;
            this.next = next;
        }

        public int Value
        {
            get { return value; }
        }

        public eRatValue Next
        {
            get { return next; }
        }

        public static implicit operator int(eRatValue eRatValue)
        {
            return eRatValue.Value;
        }
    }
    #endregion
}

This allows you to do this:

int something = eRat.A + eRat.B;

and this

eRat.eRatValue current = eRat.A;
while (current != null)
{
    Console.WriteLine(current.Value);
    current = current.Next;
}

You really should only be using enums when you can benefit from their type safety. If you're relying on them to represent a type, switch to constants or to classes.

EDIT

I would suggest you take a look at the MSDN page on Enumeration Design. The first best practice is:

Do use an enumeration to strongly type parameters, properties, and return values that represent sets of values.

I try not to argue dogma, so I won't, but here's the problem you're going to face. Microsoft doesn't want you to do what you are trying to do. They explicitly ask you not to do what you are trying to do. The make it hard for you to do what you are trying to do. In order to accomplish what you are trying to do, you have to build utility code to force it to appear to work.

You have called your solution elegant more than once, and it might be if enums were designed in a different way, but since enums are what they are, your solution isn't elegant. I think that chamber music is elegant, but if the musicians didn't have the proper instruments and had to play Vivaldi with sawblades and jugs, it would no longer be elegant, regardless of how capable they were as musicians, or how good the music was on paper.

2
  • 1
    Looking at this, I wish I could give it another +1. It seems so obvious looking at it, but I don't think I've ever really done such a thing.
    – Greg D
    Commented Mar 13, 2009 at 15:04
  • Please, check my Answer where I explain why I need an enum. If you can see a solution working in that context I would be more than happy to accept it.
    – husayt
    Commented Mar 13, 2009 at 18:46
12

Works up to "C" since there is no answer on what to return after "D".

[update1]: Updated according to Marc Gravell's suggestion.

[update2]: Updated according to how husayt's wanted - return "A" for the next value of "D".

public class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Next enum of A = {0}", eRatEnumHelper.GetNextEnumValueOf(eRat.A));
        Console.WriteLine("Next enum of B = {0}", eRatEnumHelper.GetNextEnumValueOf(eRat.B));
        Console.WriteLine("Next enum of C = {0}", eRatEnumHelper.GetNextEnumValueOf(eRat.C));
    }
}

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

public class eRatEnumHelper
{
    public static eRat GetNextEnumValueOf(eRat value)
    {
        return (from eRat val in Enum.GetValues(typeof (eRat)) 
                where val > value 
                orderby val 
                select val).DefaultIfEmpty().First();
    }
}

Result

Next enum of A = B
Next enum of B = C
Next enum of C = D
Next enum of D = A

2
  • btw; .Take(1).ToArray()[0] - could just be .First() Commented Mar 13, 2009 at 14:18
  • OMG. If another guy tells me C# is better than C++ I'll show him this sample, to show (1) that you cant get easily a next or prev enum in C# and (2) you can do a select for this. Oh my god! (this is not about you, but about what you can do in C#: some will tell it's good to do whatever you want, some will tell it's evil. IMHO this is evil.) Commented Jan 6, 2018 at 0:52
7

Thanks you all, for your inspiration and solutions.

Here are my results, as an extension.

using System; 
using System.Linq;

public static class Enums
{
    public static T Next<T>(this T v) where T : struct
    {
        return Enum.GetValues(v.GetType()).Cast<T>().Concat(new[] { default(T) }).SkipWhile(e => !v.Equals(e)).Skip(1).First();
    }

    public static T Previous<T>(this T v) where T : struct
    {
        return Enum.GetValues(v.GetType()).Cast<T>().Concat(new[] { default(T) }).Reverse().SkipWhile(e => !v.Equals(e)).Skip(1).First();
    }
}

use:

using System; 
using System.Linq;

public enum Test { F1, F2, F3 }

public class Program
{
    public static void Main()
    {
        Test t = Test.F3;   
        
        Console.WriteLine(t);
        Console.WriteLine(t.Next());
        Console.WriteLine(t.Previous());
        
        Console.WriteLine("\n");
        
        t = Test.F1;    
        Console.WriteLine(t);
        Console.WriteLine(t.Next());
        Console.WriteLine(t.Previous());
    }
}

result:

F3
F1
F2

F1
F2
F3
3
  • 2
    Don't forget to write using System; and using System.Linq;. Commented Apr 5, 2021 at 5:36
  • 2
    @user2513149 thank you for your info, fixed it here. Don't know why that was missing. Commented Apr 8, 2021 at 18:33
  • 1
    Upvote for including imports in the code! :-) Seriously, somehhow it starts to get "hip" to not show the imports. Commented May 10, 2022 at 15:02
4

Are you locked into using an enum by something that you have no control over?

If you're not, I'd suggest using an alternative, probably Dictionary<string, int> rat;

If you create a Dictionary and you populate it with your data, enumerating over it is somewhat simpler. Also, it's a clearer mapping of intent-- you're mapping numbers to strings with this enum and you're trying to leverage that mapping.

If you must use the enum, I'd suggest something else:

var rats = new List<eRat>() {eRat.A, eRat.B, eRat.C, eRat.D};

As long as you're adding the values in-order and you keep it in sync, you greatly simplify the act of retrieving the next eRat.

0
4

For simple solution, you might just extract array from enum.

eRat[] list = (eRat[])Enum.GetValues(typeof(eRat));

Then you can enumerate

foreach (eRat item in list)
    //Do something

Or find next item

int index = Array.IndexOf<eRat>(list, eRat.B);
eRat nextItem = list[index + 1];

Storing the array is better than extracting from enum each time you want next value.

But if you want more beautiful solution, create the class.

public class EnumEnumerator<T> : IEnumerator<T>, IEnumerable<T> {
    int _index;
    T[] _list;

    public EnumEnumerator() {
        if (!typeof(T).IsEnum)
            throw new NotSupportedException();
        _list = (T[])Enum.GetValues(typeof(T));
    }
    public T Current {
        get { return _list[_index]; }
    }
    public bool MoveNext() {
        if (_index + 1 >= _list.Length)
            return false;
        _index++;
        return true;
    }
    public bool MovePrevious() {
        if (_index <= 0)
            return false;
        _index--;
        return true;
    }
    public bool Seek(T item) {
        int i = Array.IndexOf<T>(_list, item);
        if (i >= 0) {
            _index = i;
            return true;
        } else
            return false;
    }
    public void Reset() {
        _index = 0;
    }
    public IEnumerator<T> GetEnumerator() {
        return ((IEnumerable<T>)_list).GetEnumerator();
    }
    void IDisposable.Dispose() { }
    object System.Collections.IEnumerator.Current {
        get { return Current; }
    }
    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
        return _list.GetEnumerator();
    }
}

Instantiate

var eRatEnum = new EnumEnumerator<eRat>();

Iterate

foreach (eRat item in eRatEnum)
    //Do something

MoveNext

eRatEnum.Seek(eRat.B);
eRatEnum.MoveNext();
eRat nextItem = eRatEnum.Current;
4

Judging from your description, you don't really want an enum. You're stretching enum beyond its capabilities. Why not create a custom class that exposes the values you need as properties, while keeping them in OrderedDictionary. Then getting a next/previous one would be trivial. --update

If you want to enumerate differently on the collection based in the context, make that explicit part of your design. Encapsulate the items within a class, and have few methods each returning IEnumerable where, T is your desired type.

For example

IEnumerable<Foo> GetFoosByBar()
IEnumerable<Foo> GetFoosByBaz()

etc...

4
  • 1
    Good suggestion - rather than overload the enum. Commented Mar 13, 2009 at 14:18
  • I don't get it. Why would you want to foreach on an enum? Can you give some more context here? Commented Mar 13, 2009 at 14:53
  • not on an enum itself. but to be able to enumerate through array members differently. I use enums as fixed indexers.
    – husayt
    Commented Mar 13, 2009 at 15:51
  • check my answer, for more detailed explanation. Thanks.
    – husayt
    Commented Mar 13, 2009 at 16:46
3

You could simplify it and generalize it some:

static Enum GetNextValue(Enum e){
    Array all = Enum.GetValues(e.GetType());
    int i = Array.IndexOf(all, e);
    if(i < 0)
        throw new InvalidEnumArgumentException();
    if(i == all.Length - 1)
        throw new ArgumentException("No more values", "e");
    return (Enum)all.GetValue(i + 1);
}

EDIT: Note that if your enum contains duplicate values (synonymous entries), then this (or any other technique listed here) will fail, given one of those values. For instance:

enum BRUSHSTYLE{
    SOLID         = 0,
    HOLLOW        = 1,
    NULL          = 1,
    HATCHED       = 2,
    PATTERN       = 3,
    DIBPATTERN    = 5,
    DIBPATTERNPT  = 6,
    PATTERN8X8    = 7,
    DIBPATTERN8X8 = 8
}

Given either BRUSHSTYLE.NULL or BRUSHSTYLE.HOLLOW, the return value would be BRUSHSTYLE.HOLLOW.

<leppie>

Update: a generics version:

static T GetNextValue<T>(T e)
{
  T[] all = (T[]) Enum.GetValues(typeof(T));
  int i = Array.IndexOf(all, e);
  if (i < 0)
    throw new InvalidEnumArgumentException();
  if (i == all.Length - 1)
    throw new ArgumentException("No more values", "e");
  return all[i + 1];
}

</leppie>

@leppie:

Your generic version allows one to accidentally pass a non-enum value, which will be caught only at run-time. I had originally written it as a generic, but when the compiler rejected where T : Enum, I took it out and realized that I wasn't gaining much from generics anyway. The only real drawback is that you have to cast the result back to your specific enum type.

6
  • Come on! Generic, without generics! Dont be lazy :)
    – leppie
    Commented Mar 13, 2009 at 13:22
  • @leppie: Please see comment within post.
    – P Daddy
    Commented Mar 13, 2009 at 13:53
  • You can add a check inside the method. OR you dont have to as it will blow up anyways :)
    – leppie
    Commented Mar 13, 2009 at 14:06
  • My point was that the non-generic version will catch your mistake at compile time. I always prefer catching errors at compile time over catching them at run time.
    – P Daddy
    Commented Mar 13, 2009 at 14:20
  • to make generic version more safe you can put "where T : struct" and then " if (!typeof(T).IsEnum) throw new ArgumentException(String.Format("Argumnent {0} is Not an Enum", typeof(T).FullName)); " to enforce it further
    – husayt
    Commented Mar 13, 2009 at 16:12
3

There is a very simple solution (if you can change your integer values) that is specifically designed to work with numbers. The fact that your number is an enum, isn't a problem. It is still the integer (or whatever underlying number type you assign). Enum just adds the complexity of a cast requirement.

Assume your enum is defined like this:

 public enum ItemStatus
    {
        New = 0,
        Draft = 1,
        Received = 2,
        Review = 4,
        Rejected = 8,
        Approved = 16
    }

ItemStatus myStatus = ItemStatus.Draft;

Use bitwise operations on the Enum. For Example:

myStatus = (ItemStatus)(((int)myStatus) << 1)

The result is of myStatus is: ItemStatus.Received.

You can also go backwards down the Enum by changing the bitwise operator from << to >>.

myStatus = (ItemStatus)(((int)myStatus) >> 1)

The result is of myStatus is: ItemStatus.New.

You should always add code to test for an "out of bounds" situation in both directions.

You can understand more about bitwise operations here: http://code.tutsplus.com/articles/understanding-bitwise-operators--active-11301

2
  • 1
    There is a MORE simple solution (if you can change your integer values) that is specifically designed to work with numbers: NATURAL NUMBERS! If you use 1, 2, 3, 4, 5... You can do mystatus++ or mystatus--. Tha matter is that he needs those numbers: 0, 3, 5...
    – tedebus
    Commented Nov 30, 2017 at 9:35
  • This is not working as expected just tested this and it returns wrong values.
    – Payam
    Commented Oct 25, 2018 at 15:05
2

Hope this part of my code helps you:

public enum EGroupedBy
{
    Type,
    InterfaceAndType,
    Alpha,
    _max
}

private void _btnViewUnit_Click(object sender, EventArgs e)
{
    int i = (int)GroupedBy;

    i = (i + 1) % (int)EGroupedBy._max;

    GroupedBy = (EGroupedBy) i;

    RefreshUnit();
}
1
  • I simplified to a single line - GroupedBy = (EGroupedBy)(((int)GroupedBy + 1) % (int)EGroupedBy._max);
    – simo.3792
    Commented Nov 4, 2016 at 3:45
2

Old post, but I have an alternative solution

//Next with looping    
public static Enum Next(this Enum input)
{
    Array Arr = Enum.GetValues(input.GetType());
    int j = Array.IndexOf(Arr, input) + 1;
    return (Arr.Length == j) ? (Enum)Arr.GetValue(0) : (Enum)Arr.GetValue(j);
}

//Previous with looping
public static Enum Prev(this Enum input)
{
   Array Arr = Enum.GetValues(input.GetType());
   int j = Array.IndexOf(Arr, input) - 1;
   return (j == -1) ? (Enum)Arr.GetValue(Arr.Length -1) : (Enum)Arr.GetValue(j);
}

And when you need to use it, just do a cast

BootstrapThemeEnum theme = BootstrapThemeEnum.Info;
var next = (BootstrapThemeEnum)theme.Next();

my enum

public enum BootstrapThemeEnum
{
    [Description("white")]
    White = 0,
    [Description("default")]
    Default = 1,
    [Description("info")]
    Info = 2,
    [Description("primary")]
    Primary = 3,
    [Description("success")]
    Success = 4,
    [Description("warning")]
    Warning = 5,
    [Description("danger")]
    Danger = 6,
    [Description("inverse")]
    Inverse = 7

}
1

I can think of 2 things:

  • eRat.B+3
  • Enum.Parse(typeof(((int)eRat.B)+3)
3
  • because public enum eRat { A = 0, B=3, C=5, D=8 }; A =0, B=3 so the next one is a +3
    – RvdK
    Commented Mar 13, 2009 at 13:30
  • Yes, but solution should be universal. it should work for any enum. Would it work for A in our case?? I just want next enum member.
    – husayt
    Commented Mar 13, 2009 at 14:17
  • indeed, i was apperently sleeping :P sorry
    – RvdK
    Commented Mar 14, 2009 at 16:26
1

var next = (eRat)((int)someRat + 3);

2
  • Thanks, but not. we are looking for universal solution. it wouldn't work for A, for instance.
    – husayt
    Commented Mar 13, 2009 at 14:19
  • @husayt it works for A, (0+3) = B :) - to make it work completely just split it a bit and check it doesn't go above the last one.
    – eglasius
    Commented Mar 13, 2009 at 16:50
1

Seems like an abuse of the enum class to me - but this would do it (assuming that calling Next on the last value would cause wrap-around):

public static eRat Next(this eRat target)
{
    var nextValueQuery = Enum.GetValues(typeof(eRat)).Cast<eRat>().SkipWhile(e => e != target).Skip(1);
    if (nextValueQuery.Count() != 0)
    {
        return (eRat)nextValueQuery.First();
    }
    else
    {
        return eRat.A;
    }
}

And this would give you the previous value on the same basis:

public static eRat Previous(this eRat target)
{
    var nextValueQuery = Enum.GetValues(typeof(eRat)).Cast<eRat>().Reverse().SkipWhile(e => e != target).Skip(1);
    if (nextValueQuery.Count() != 0)
    {
        return (eRat)nextValueQuery.First();
    }
    else
    {
        return eRat.D;
    }
}
1

I'm using this, perfect for my.

    //===================================================================================
// NEXT VALUE IN ENUM 
// ex: E_CamModes eNew =  kGlobalsVars.eGetNextValue< E_CamModes >( geCmMode );
public static T eGetNextValue< T >( T eIn ){
    T[] aiAllValues = ( T[] ) Enum.GetValues( typeof( T ));
    int iVal = System.Array.IndexOf( aiAllValues, eIn );
    return aiAllValues[ ( iVal + 1 ) % aiAllValues.Length ];
}
0

I would go with Sung Meister's answer but here is an alternative:

MyEnum initial = MyEnum.B, next;

for (int i = ((int) initial) + 1, i < int.MaxValue; i++)
{
  if (Enum.IsDefined(typeof(MyEnum), (MyEnum) i))
  {
     next = (MyEnum) i;
     break;
  }
}

Note: many assumptions assumed :)

0

From comments I had many question like: "Why would you ever want to use enum in this way." Since so many of you asked, let me give you my use case and see if you agree then:

I have a fixed array of items int[n]. Depending on the situation I want to enumerate through this array differently. So i defined:

int[] Arr= {1,2,34,5,6,78,9,90,30};
enum eRat1 { A = 0, B=3, C=5, D=8 }; 
enum eRat2 { A, AA,AAA,B,BB,C,C,CC,D }; 

void walk(Type enumType) 
{ 
   foreach (Type t in Enum.GetValues(enumType)) 
   { 
      write(t.ToString() + " = " + Arr[(int)t)]; 
   }
} 

and call walk(typeof(eRAt1)) or walk(typeof(eRAt2))

then i get required output

1) walk(typeof(eRAt1))

A = 1
B = 5
C = 78
D = 30

2) walk(typeof(eRAt2))

A = 1
AA = 2
AAA = 34
B = 5
BB = 6
C = 78
CC = 90
D = 30

This is very simplified. But i hope, this explains. There are some other advantages to this, as having enum.toString(). So basically i use enums as indexers.

So using the solution I can do something like this now.

In sequence eRat1 next value to B is C, but in eRat2 it is BB. So depending on which sequence I am interested in, I can do e.next and depending on enumType I will either get C or BB. How would one achieve that with dictionaries?

I think this a rather elegant use of enums.

7
  • They problem you're going to face (I argue this from the point of practicality, not dogma) is that you're trying to force enums do something that they are specifically designed to not do (represent an int). It may feel elegant, but you'll find that the workaround discussed here won't be your last. Commented Mar 13, 2009 at 17:54
  • I use Enums for enumerating (That is what their name suggest anyway). I use them as indexers, not just as a mere integers. Ok. Imagine chess board :A,B,C,..,E,F,G,H One figure moves A->C->D->F Another B->C->E->H Third C->A->B->G now enums would most elegant way to describe all these movements
    – husayt
    Commented Mar 13, 2009 at 18:37
  • I got what you were saying, but enums are not for enumerating, even though the names look similar. Enums are for representing values free of type (even though you can define an underlying type). I'll update my answer to further exposit Commented Mar 13, 2009 at 19:35
  • Anyway, how would the solution would look, without enums??
    – husayt
    Commented Mar 13, 2009 at 19:38
  • 1
    @husayt: Arrays are indexed with integers. A set of array index values should be an integer array, not an enum. Without enums the solution has less casting and passes a constant array of index values in order to do a 'walk' instead of passing a type parameter. Did not The Beatles say it first? 'All you need is int'! ... Well, maybe they didn't say that.
    – Task
    Commented Mar 25, 2010 at 16:32
0

I'm using this here:

public MyEnum getNext() {
    return this.ordinal() < MyEnum.values().length - 1 ? 
                            MyEnum.values()[this.ordinal() + 1] : 
                            MyEnum.values()[0];
}
1
  • Am I missing something? I can't find ordinal() Commented Feb 6, 2018 at 22:43
0

LINQ solution that does not break on last element but continues at the default again:

var nextValue = Enum.GetValues(typeof(EnumT)).Cast<EnumT>().Concat(new[]{default(EnumT)}).SkipWhile(_ => _ != value).Skip(1).First();
1
  • 1
    not working as expected. The return type is not the "next" enum
    – Payam
    Commented Oct 25, 2018 at 15:07
0

I tried the first solution but it did not work for me. Below is my solution:

    public  object NextEnumItem(object currentEnumItem) 
    {
        if (!currentEnumItem.GetType().IsEnum) throw new 
                ArgumentException(String.Format("Argument is not an Enum"));
        Array Arr = Enum.GetValues(currentEnumItem.GetType());
        int j = Array.IndexOf(Arr,currentEnumItem) + 1;
        return (Arr.Length == j) ? currentEnumItem : Arr.GetValue(j);
    }

    public object PreviousEnumItem(object currentEnumItem)
    {
        if (!currentEnumItem.GetType().IsEnum)
            throw new ArgumentException(String.Format("Argument is not an Enum"));
        Array Arr = Enum.GetValues(currentEnumItem.GetType());
        int j = Array.IndexOf(Arr, currentEnumItem) - 1;
        return (j==-1) ? currentEnumItem : Arr.GetValue(j);
    }
0

I did something similar with a different enum. It's for a game and the player has the chance to toggle colors.

public enum PlayerColor {
    Red = 0, Green, Blue, Cyan, Yellow, Orange, Purple, Magenta
}

public PlayerColor GetNextFreeColor(PlayerColor oldColor) {

    PlayerColor newColor = (PlayerColor)((int)(oldColor + 1) % 8);
    return newColor;
}

This solution worked for me.

0

Based on best answer from Yahya Hussein here is edit of his code for Previous element in Enum

public static class Extensions
{
    public static T Previous<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 (j < 0) ? Arr[Array.Length - 1] : Arr[j];            
    }
}
1
  • I think the last line should be "Arr.Length": return (j < 0) ? Arr[Arr.Length - 1] : Arr[j]; - Otherwise your implementation seems to work.
    – olijake
    Commented May 5, 2023 at 23:49
0
enum Level
{
    Easy,
    Medium,
    Expert
};

public static void Main()
{
    var difficulty = Level.Easy;
    var level = (int)difficulty;
    Console.WriteLine(difficulty);

    Console.WriteLine(level);
    Console.WriteLine("promote level");
    level++;

    Console.WriteLine(level);
    difficulty = (Level)level;

    Console.WriteLine(difficulty);
}
-1

You can add and remove integers to an enum to obtain the next value. The only problem is that integer operations on the enum will not check the validity of the enum itself, thus could set "invalid" values.

But you can combine the ++enum and the Enum.IsDefined() to obtain a simple way to get next and previous values of your enum. This would be inefficient in your case since the integer values are not continuous, but if you have continuous integers then it works nicely, and one can check when the ++enum is out of range. Check the next example.

 public enum level
    {
        a = 0,
        b = 1,
        c = 2,
        d = 3,
        e = 4
    }

private static void Main(string[] args)
    {
        var levelValue = level.a;
        Console.WriteLine(levelValue);
        ++levelValue;
        Console.WriteLine(levelValue);
        ++levelValue;
        Console.WriteLine(levelValue);
        ++levelValue;
        Console.WriteLine(levelValue);
        ++levelValue;
        Console.WriteLine(levelValue);
        ++levelValue;
        Console.WriteLine(Enum.IsDefined(typeof(Program.level), levelValue));
        Console.WriteLine(levelValue);
        --levelValue;
        Console.WriteLine(levelValue);
        --levelValue;
        Console.WriteLine(levelValue);
        --levelValue;
        Console.WriteLine(levelValue);
        --levelValue;
        Console.WriteLine(levelValue);
        --levelValue;
        Console.WriteLine(Enum.IsDefined(typeof(Program.level), levelValue));
        Console.WriteLine(levelValue);
        --levelValue;
        Console.WriteLine(Enum.IsDefined(typeof(Program.level), levelValue));
        Console.WriteLine(levelValue);
    }

The output for this would be:

a
b
c
d
e
False
5
e
d
c
b
True
a
False
-1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.