C
C#17mo ago
triplemocha

❔ 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
Aaron17mo ago
you want GetValues, not GetNames
TheRanger
TheRanger17mo ago
iirc its return (T)(object)Rand.Next
Aaron
Aaron17mo ago
and also that well, no okay
triplemocha
triplemochaOP17mo 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
Aaron17mo 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
triplemochaOP17mo ago
I got this message:
Aaron
Aaron17mo ago
did you get the edit I made I swapped it from T : Enum to T : struct
triplemocha
triplemochaOP17mo ago
I did.
TheRanger
TheRanger17mo ago
remove the - 1 or ull never get the last value
Aaron
Aaron17mo ago
no that just doesn't work
enum E
{
Value = 50
}
enum E
{
Value = 50
}
triplemocha
triplemochaOP17mo ago
Same thing. It's a custom Random class I made, so last value is max - 1.
TheRanger
TheRanger17mo 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
Aaron17mo 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
triplemochaOP17mo ago
Seems to be working. Thanks! unmanaged is new to me.
Aaron
Aaron17mo 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
TheRanger17mo ago
works
triplemocha
triplemochaOP17mo ago
Ah, I see.
Accord
Accord17mo 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.
Want results from more Discord servers?
Add your server