Skip to content

Instantly share code, notes, and snippets.

@xv
Last active October 28, 2025 03:32
Show Gist options
  • Save xv/81eea2697288c931e14186811390191d to your computer and use it in GitHub Desktop.
Save xv/81eea2697288c931e14186811390191d to your computer and use it in GitHub Desktop.
Cycles through an enum upward or downward and clamps the index.
private static T CycleEnum<T>(T type, int direction) where T : Enum
{
var values = (T[])Enum.GetValues(typeof(T));
var index = Array.IndexOf(values, type);
var newIndex = Math.Clamp(index + direction, 0, values.Length - 1);
return values[newIndex];
}
private enum TestEnum
{
Foo = 1,
Bar = 3,
Baz = 5,
Qux = 7
}
private TestEnum Test {get; set;}
private void CycleTestUp() => Test = CycleEnum(Test, -1);
private void CycleTestDown() => Test = CycleEnum(Test, +1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment