❔ 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);
        }
Was this page helpful?