Search code examples
c#enumsextension-methods

random enum value for a generic enum type extension method


Id like to write an extension method for any Enum that returns a random value from that enum, currently ive got this:

class Monster
{
    public enum presets
    {
     //some values
    }
    presets p = presets.randomEnum();
}
public static class Extensions
{
        public static T randomEnum<T>(this T en) where T : struct , IConvertible , IEnumerable<Enum>
        {
            if (!typeof(T).IsEnum) { throw new Exception("random enum variable is not an enum"); }
            Array values = en.ToArray();
            return (T)values.GetValue(Random.Next(values.Length));
        }
}

but when i do presets.randomEnum() Visual Studio 19 tells me that Error CS0117 'Monster.presets' does not contain a definition for 'randomEnum'

NOTE: i had to do ALOT of googling for that ext method so if theres an easier way that i missed or just didn't think of, id greatly appreciate it


Solution

  • The extension method must be defined at the top of the class (i.e. inside of a namespace but not in another class). Also, you can't have that IEnumerable constraint on it, it is too much. This works for me:

     public enum Presets
        {
            Test,
            Test2
        }
    
    
        public static class Extensions
        {
            public static T RandomEnum<T>(this T en) where T : struct, IConvertible
            {
                if (!typeof(T).IsEnum) { throw new Exception("random enum variable is not an enum"); }
    
                var random = new Random();
                var values = Enum.GetValues(typeof(T));
                return (T)values.GetValue(random.Next(values.Length));
            }
        }