© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
29 replies
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);
        }
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

✅ How to set enum default int value
C#CC# / help
3y ago
❔ Attributes on a enum value?
C#CC# / help
3y ago
❔ Compare Enum Values with submitted value
C#CC# / help
4y ago