tags:

views:

52

answers:

2

I need some input.

Say you have an int-based Enum with values 1 through 10. If you then have a variable that is, say, value corresponding to 7, how can you easiest set it to next value in the given range without going out of bounds? If the value reaches the limit, it should reset itself to first in the range.

I want a one-liner solution to this. I don't want to do ++ and then check and reset value, plus it has to work in both C# and JavaScript. I suppose something in the Math object might be of help, I don't know...

thanks

+4  A: 

Increment, subtract 1, then modulo, then add 1 (since your Enum is 1-based).

((++i - 1) % N + 1

(N=10, the maximum value your Enum can take on.)

larsmans
that's the one! thanks dude.
danijels
You're welcome. This is my first line of C#, btw. :)
larsmans
A: 

If you know the limits and are sure that all numbers between 0 and that upper limit is occupied by an enum you can use the modulo operator

myEnum = (myEnum + 1) % maxValue;

You may need to typecast:

myEnum = (MyEnumType) (((int) myEnum + 1) % maxValue);

EDIT: I noticed you have one-based enums. If you really need this, then you would have to do as larsman suggests in his answer:

// This statement may look weird, but it works :)
myEnum = (myEnum % maxValue) + 1
// Produces (for myEnum with maxValue set to 4, i.e. allows 1,2,3 & 4 as valid values):
//  1 => 2
//  2 => 3
//  3 => 4
//  4 => 1
Isak Savo