Given an enum that has assigned values, what is the best way to get the next or previous enum given a value. For example, consider this enum:
public enum TimeframeType {
None = 0,
[Description("1 month")]
Now = 30,
[Description("1-3 months")]
Short = 90,
[Description("3-6 months")]
Medium = 180,
[Description("6+ months")]
Long = 360
}
Is there a good way create a function that would do EnumPrevious(TimeframeType.Short) returns TimeframeType.Now and EnumNext(TimeframeType.Short) would return TimeframeType.Medium?
I already wrote an ugly implementation of EnumNext but I'm not convinced that it is the best way to do so. I'm hoping someone else has already tackled this problem.
public static T EnumNext<T>(T value) where T : struct {
T[] values = (T[])Enum.GetValues(typeof(T));
int i;
for (i = 0; i < values.Length; i++) {
if (object.Equals(value, values[i])) {
break;
}
}
if (i >= values.Length - 1) {
return values[values.Length - 1];
} else {
return values[i + 1];
}
}