How to get next (or previous) enum value in C#
Thanks to everybody for your answers and feedback. I was surprised to get so many of them. Looking at them and using some of the ideas, I came up with this solution, which works best for me:
public static class Extensions
{
public static T Next<T>(this T src) where T : struct
{
if (!typeof(T).IsEnum) throw new ArgumentException(String.Format("Argument {0} is not an Enum", typeof(T).FullName));
T[] Arr = (T[])Enum.GetValues(src.GetType());
int j = Array.IndexOf<T>(Arr, src) + 1;
return (Arr.Length==j) ? Arr[0] : Arr[j];
}
}
The beauty of this approach, that it is simple and universal to use. Implemented as generic extension method, you can call it on any enum this way:
return eRat.B.Next();
Notice, I am using generalized extension method, thus I don't need to specify type upon call, just .Next()
.
Get Next item in Enum and return first if last+1
Add modulo arithmetics to husayt's answer
How to get next (or previous) enum value in C#
Code:
public static class Extensions {
public static T Next<T>(this T src) where T : struct {
if (!typeof(T).IsEnum)
throw new ArgumentException(String.Format("Argument {0} is not an Enum",
typeof(T).FullName));
T[] Arr = (T[])Enum.GetValues(src.GetType());
int j = (Array.IndexOf<T>(Arr, src) + 1) % Arr.Length; // <- Modulo % Arr.Length added
return Arr[j];
}
}
How to select next enum value ?
Well first set today = DayName.Friday
and then print(today.ToString()
after the today ++ ;
As descirbed at this SO post, Enum String Name from Value
Get next enum based on the order they are rather than name or value?
public Something GetNextEnum(Something e)
{
switch(e)
{
case This:
return That;
case That:
return It;
case It:
return This;
default:
throw new IndexOutOfRangeException();
}
}
Or make it an extension:
public static class MySomethingExtensions {
public static Something GetNextEnum(this Something e)
{
switch(e)
{
case This:
return That;
case That:
return It;
case It:
return This;
default:
throw new IndexOutOfRangeException();
}
}
}
and you can use it like this:
_status=_status.GetNextEnum();
Next or previous enum
You are trying to solve the wrong problem. This is far too complex for a simple enum to calculate. Refactor the enum to a class and use a comparison interface.
If this route is open to you look at how this could be implemented by a class:
public class TimeFrame: IComparable
{
private int days;
public int Days
{
set
{
days = value;
}
}
public int CompareTo(object other)
{
//see this for implementation -- http://msdn.microsoft.com/en-us/library/system.icomparable.aspx#Mtps_DropDownFilterText
}
public string Description
{
get code to return the description string , ie "1-3 months"
}
}
Get int value from enum in C#
Just cast the enum, e.g.
int something = (int) Question.Role;
The above will work for the vast majority of enums you see in the wild, as the default underlying type for an enum is int
.
However, as cecilphillip points out, enums can have different underlying types.
If an enum is declared as a uint
, long
, or ulong
, it should be cast to the type of the enum; e.g. for
enum StarsInMilkyWay:long {Sun = 1, V645Centauri = 2 .. Wolf424B = 2147483649};
you should use
long something = (long)StarsInMilkyWay.Wolf424B;
Android Get the next or previous Enum
//Store these somewhere in your class
Mode[] modes = Mode.values();
int modeCount = modes.length;
protected void onClick(View v) {
//Get the next mode, wrapping around if you reach the end
int nextModeOrdinal = (m.ordinal() + 1) % modeCount;
m = modes[nextModeOrdinal];
}
For Kotlin, you can declare an extension function on all enum types that would allow you to define a next()
function on all enum instances:
/**
* Returns the next enum value as declared in the class. If this is the last enum declared,
this will wrap around to return the first declared enum.
*
* @param values an optional array of enum values to be used; this can be used in order to
* cache access to the values() array of the enum type and reduce allocations if this is
* called frequently.
*/
inline fun <reified T : Enum<T>> Enum<T>.next(values: Array<T> = enumValues()) =
values[(ordinal + 1) % values.size]
Then you can have something like:
enum class MyEnum {
ONE, TWO, THREE
}
Then you can just use val two = MyEnum.ONE.next()
Iterate Between Enum Values in C#
This will work:
for(Cars car=Cars.Opel; car<=Cars.Citroen; car++)
{
Console.WriteLine(car);
}
but you have to make sure that the start value is less than the end value.
EDIT
If you don't hardcode the start and end, but supply them as parameters, you need to use them in the correct order. If you just switch "Opel" and "Citroen", you will get no output.
Also (as remarked in the comments) the underlying integer values must not contain gaps or overlaps. Luckily if you do not specify values yourself (even the '=0' is not needed), this will be the default behaviour. See MSDN:
When you do not specify values for the elements in the enumerator list, the values are automatically incremented by 1.
Related Topics
Converting Integers to Roman Numerals
What Are the Differences Between the Xmlserializer and Binaryformatter
How Are Nullable Types Implemented Under the Hood in .Net
Differencebetween Xamarin.Form's Layoutoptions, Especially Fill and Expand
How to Expand a String That Contains C# Literal Expressions at Runtime
Microsoft Visual Studio and C#: How to Visually Add Events to Controls
How to Overload the [] Operator in C#
C# Marking Class Property as Dirty
Getting Correct Image Rotation
Convert Datatable to Ienumerable<T>
Calculating Hmacsha256 Using C# to Match Payment Provider Example
When Not to Use Yield (Return)
Where Is My System.Numerics Namespace
Case Insensitive Regex Without Using Regexoptions Enumeration