Question Details

No question body available.

Tags

c# enums

Answers (1)

May 7, 2026 Score: 3 Rep: 1,526,821 Quality: Medium Completeness: 70%

Your syntax and generic constraints are both slightly off:

  • You still need to put the type you're extending within the parentheses, so extension(T)
  • You need to constrain T to be a non-nullable value type as well (in order to call Enum.GetValues(), so where T : struct, Enum

This compiles (assuming a suitable Choice method):

public static class Extensions
{
    extension(T) where T : struct, Enum
    {
        public static T Random => Enum.GetValues().Choice();
    }
}

I'd recommend making this a method rather than a property though.