C
C#2mo ago
Cykotech

Iterate through Enums

If I want to make an action iterate through an enum everytime it's taken, obviously I would just use object++; but what do I except when I reach the max value and want it to return back to the min value? And if a simple increment doesn't work how would I loop through the enum as such?
12 Replies
Buddy
Buddy2mo ago
iterate through an enum in what way? You can use this https://learn.microsoft.com/en-us/dotnet/api/system.enum.getvalues?view=net-9.0 And then iterate them that way. or if they follow the default pattern of 0, 1, 2, 3 .. you can just do a for-loop and cast the integer to the specified enum
Cykotech
CykotechOP2mo ago
I would essentially want to go 0, 1, 2, 3, 0, 1....
Buddy
Buddy2mo ago
How many times? You can just use index = i % totalEnumCount % is the remainder https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/arithmetic-operators#remainder-operator-
Cykotech
CykotechOP2mo ago
The number of times is irrelevant. The enum would only change when an action is taken. But I could do something like this?
void changeEnum()
{
randomEnum = randomEnum + 1 % 4;
}
void changeEnum()
{
randomEnum = randomEnum + 1 % 4;
}
I picked 4 because that's the length of my enum.
Buddy
Buddy2mo ago
why + 1?
Cykotech
CykotechOP2mo ago
Cuz I want the next enum. And the modulo would keep the value within the bounds of the enum? Can I apply further calculations after using the increment operator? randomEnum++ % 4
sibber
sibber2mo ago
no % takes precedence
Cykotech
CykotechOP2mo ago
So I'd have to calculate the index, then apply the modulo. In seperate equations.
canton7
canton72mo ago
Why? Just x = (x + 1) % Length
TheRanger
TheRanger2mo ago
what if enum is like this
public enum Foo
{
a = 1
b = 16
c = 128
}
public enum Foo
{
a = 1
b = 16
c = 128
}
i dont think increment would work with that enum
MODiX
MODiX2mo ago
Buddy
Quoted by
<@203166497198047232> from #Iterate through Enums (click here)
React with ❌ to remove this embed.
Buddy
Buddy2mo ago
But yes, you are right. It wouldn't work that way. But you can access their values and do it against the index of the values and then cast that to the enum

Did you find this page helpful?