5

Possible Duplicate:
Create Generic method constraining T to an Enum

is it possible to create a generic method that takes in any enum? I'll then check the incoming type to first make sure it's an enum that was passed (or can I enforce that natrually through the method definition?) and second then if it's an enum, I will have a bunch of case statements that do stuff based on what type of enum that was passed. So for example I can pass it CompanyColumns, PayColumns, etc. which are enums. My method needs to be able to take any enum like this and allow me to then work with the enum in my internal case statement.

public static DbType GetColumnDataType(I want to be able to pass in any object that's an enum)

Community
  • 1
  • 1
PositiveGuy
  • 46,620
  • 110
  • 305
  • 471

2 Answers2

11
public static void MyFunction<T>(T en) where T: IComparable, IFormattable, IConvertible
{
    if (!typeof(T).IsEnum)
        throw new ArgumentException("en must be enum type");
    // implementation
}
Denis
  • 5,894
  • 3
  • 17
  • 23
  • thanks. And so if I want to work with the enum in a case statement I tried doing this, not sure how switch ((enum)T) – PositiveGuy Oct 22 '12 at 19:00
5

try this:

public static DbType GetColumnDataType(Enum en){...}

that's not generic, but well work.

if you want generic you could do the following:

public DbType GetColumnDataType<T>(T en)
{
    Type t = n.getType();
    if (!t.isEnum)
    {
      //through exception 
    }
}
elyashiv
  • 3,623
  • 2
  • 29
  • 52