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