In most popular programming languages like Java and C# there is a way to define enums
, which are essentially datatypes with a fixed set of values, e.g. DayOfWeek
.
The problem is, given a value, e.g. DayOfWeek.Monday
, how do I get the next value of the enum
, in this particular case DayOfWeek.Tuesday
?
I realize that not all enums
are ordered and there might be different kinds of orders for them (cyclic, partial etc.), but a simple next
operation would be sufficient in most cases. In fact, since the set of values in a enum
is fixed and limited, this could be done completely declaratively, assuming there is a means in the language to do so. However in most programming languages that is simply not possible, at least not as easily as it could be in theory.
So, my question is: why is that so? What are the reasons for not providing a simple syntax for declaring the next
value for a enum
? I suggest, in C# or Java this could even be done with a special attribute or annotation, resp. But there are none, as far as I know.
I am explicitly not asking for workarounds; I know that there are alternative solutions. I just want to know why I have to employ a workaround in the first place.
Best Answer
It is difficult to generalize.
It is an decision made by each programming language designer / team. But note that some programming languages do provide a "next" operation for enumerated types.
In Pascal, the
succ
function returns the next value of an enumerated type, and thepred
function returns the previous value. But this only works for classic enumerated types. C-style enumerated types have "holes" in the type domain, and thesucc
andpred
functions are not allowed.Reference: http://www.freepascal.org/docs-html/ref/refse12.html#QQ2-27-32
And, in fact, that gives a clue as to why many languages with enumeration / enumerated types don't have a "next" operation. It is prohibitively expensive when you can't implement "next" by using integer addition under the hood.
Of course, in the languages that don't support
next
directly, it is always possible to implement it for yourself ... if you need it ... as some kind of helper method / function.