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
  • 84,693
  • 113
  • 396
  • 647

1 Answers1

2

Use Where T: struct

See this Question Create Generic method constraining T to an Enum

Community
  • 1
  • 1
terjetyl
  • 9,497
  • 4
  • 54
  • 72