2

i'm trying to do the following extension method -> converting an int to a enum, when you provide the enum :-

public static T ToEnum<T>(this int value)
{
    return (T)Enum.ToObject(typeof(T), value);
}

Now, i was hoping to make it so that you can only define the type T to be an enumeration. Is there any what i can restrict it?

eg.

int day = 3;
DaysOfWeek dow = day<DaysOfWeek>(); // No compiler error.
DaysOfWeek dow2 = day<Foo>(); // Compiler error.
Pure.Krome
  • 82,011
  • 105
  • 379
  • 615

1 Answers1

2

Use Where T: struct

See this Question Create Generic method constraining T to an Enum

Community
  • 1
  • 1
terjetyl
  • 9,287
  • 4
  • 53
  • 72