C
C#3w 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
Buddy3w 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
CykotechOP3w ago
I would essentially want to go 0, 1, 2, 3, 0, 1....
Buddy
Buddy3w 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
CykotechOP3w 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
Buddy3w ago
why + 1?
Cykotech
CykotechOP3w 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
sibber3w ago
no % takes precedence
Cykotech
CykotechOP3w ago
So I'd have to calculate the index, then apply the modulo. In seperate equations.
canton7
canton73w ago
Why? Just x = (x + 1) % Length
TheRanger
TheRanger3w 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
MODiX3w ago
Buddy
Quoted by
<@203166497198047232> from #Iterate through Enums (click here)
React with ❌ to remove this embed.
Buddy
Buddy3w 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
Want results from more Discord servers?
Add your server