❔ How to get a random enum value?

I have a function here where I would like to get a random value from an enum type. The goal is to give NextValue any enum type, and it will calculate its length and return a random value. The cast on return isn't working. Is this possible to do?
public static T NextValue<T>() where T : Enum
{
return (T)Rand.Next(0, Enum.GetNames(typeof(T)).Length - 1);
}
public static T NextValue<T>() where T : Enum
{
return (T)Rand.Next(0, Enum.GetNames(typeof(T)).Length - 1);
}
18 Replies
Aaron
Aaron2y ago
you want GetValues, not GetNames
TheRanger
TheRanger2y ago
iirc its return (T)(object)Rand.Next
Aaron
Aaron2y ago
and also that well, no okay
triplemocha
triplemochaOP2y ago
Appears to be working:
public static T NextValue<T>() where T : Enum
{
return (T)(object)Rand.Next(0, Enum.GetValues(typeof(T)).Length - 1);
}
public static T NextValue<T>() where T : Enum
{
return (T)(object)Rand.Next(0, Enum.GetValues(typeof(T)).Length - 1);
}
Aaron
Aaron2y ago
public static T NextValue<T>() where T : struct
{
var values = Enum.GetValues<T>();
return values[Rand.Next(0, values.Length)];
}
public static T NextValue<T>() where T : struct
{
var values = Enum.GetValues<T>();
return values[Rand.Next(0, values.Length)];
}
that
triplemocha
triplemochaOP2y ago
I got this message:
Aaron
Aaron2y ago
did you get the edit I made I swapped it from T : Enum to T : struct
triplemocha
triplemochaOP2y ago
I did.
TheRanger
TheRanger2y ago
remove the - 1 or ull never get the last value
Aaron
Aaron2y ago
no that just doesn't work
enum E
{
Value = 50
}
enum E
{
Value = 50
}
triplemocha
triplemochaOP2y ago
Same thing. It's a custom Random class I made, so last value is max - 1.
TheRanger
TheRanger2y ago
this works for me
public static T NextValue<T>() where T : Enum
{
var values = (T[])Enum.GetValues(typeof(T));
return values[Random.Shared.Next(0, values.Length)];
}
public static T NextValue<T>() where T : Enum
{
var values = (T[])Enum.GetValues(typeof(T));
return values[Random.Shared.Next(0, values.Length)];
}
Aaron
Aaron2y ago
ah okay make the constraint unmanaged, Enum
public static T NextValue<T>() where T : unmanaged, Enum
{
var values = Enum.GetValues<T>();
return values[Rand.Next(0, values.Length)];
}
public static T NextValue<T>() where T : unmanaged, Enum
{
var values = Enum.GetValues<T>();
return values[Rand.Next(0, values.Length)];
}
triplemocha
triplemochaOP2y ago
Seems to be working. Thanks! unmanaged is new to me.
Aaron
Aaron2y ago
I think struct, Enum might also work? unmanaged just means there are no objects in it, which applies so enums, so that's what I'm used to using
TheRanger
TheRanger2y ago
works
triplemocha
triplemochaOP2y ago
Ah, I see.
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.

Did you find this page helpful?