Modular increment/decrement operators #8133
Unanswered
Rabadash8820
asked this question in
Language Ideas
Replies: 1 comment 4 replies
-
could do something like: public static void IncrementAndWrap(this ref int index, int count)
{
index = (index + 1) % count;
} |
Beta Was this translation helpful? Give feedback.
4 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I often find myself writing code that has to traverse a list and "loop around". E.g., in game code, I might want to pick 5 random entities from a list of N to initiate some behavior; a naive/performant implementation is to pick 5 elements starting from a random index in the list, with modulus to avoid
IndexOutOfBoundsException
. Having a single operator to do this "increment/decrement index but loop around" would be quite handy.Here is the idea for the "modular increment operator":
A "modular decrement operator",
--%=
would work similarly. Its implementation may not be as simple asindex = (index - 1) % count
as it would have to account for negative numbers (I typically useindex = (index - 1 + count) % count
in these situations). I think it could be implemented asindex = (index - 1) %% count
if I understand the proposal in #4744 correctly.I admit, a 4-character operator is kinda ridiculous, and incrementing/decrementing by a number other than 1 would still require the same code as before. I did consider a ternary assignment operator like
index +%= delta count
but I'm not sure that's any more readable than current C# options. Anyway, just wanted to see if anyone else has considered this idea or would find it worthwhile.Beta Was this translation helpful? Give feedback.
All reactions