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