tags:

views:

87

answers:

2

I would like to do this but it does not work.

bool TryGetEnum<TEnum, TValue>(TValue value, out TEnum myEnum)
{

    value = default(TEnum);
    if (Enum.IsDefined(typeof(TEnum), value))
    {
        myEnum = (TEnum)value;
        return true;
    }
    return false;
}

Example usage:

MyEnum mye;
bool success = this.TryGetEnum<MyEnum,char>('c',out mye);
+2  A: 

The best you will be able to do is this:

bool TryGetEnum<TEnum>(Object value, out TEnum myEnum)
{
    myEnum = default(TEnum);
    if (Enum.IsDefined(typeof(TEnum), value))
    {
        myEnum = (TEnum)value;
        return true;
    }
    return false;
}

With a use case that looks something like this:

MyEnum mye;
bool success = this.TryGetEnum<MyEnum>(2, out mye);

You won't be able to make the input type generic as there are no generic constraints available for you to leverage that would enable you to guarantee that TEnum uses TValue as its underlying type.

Also, (as a side note) C# only allows the following types to be used as the underlying value for an enum:

  • byte
  • sbyte
  • short
  • ushort
  • int
  • uint
  • long
  • ulong
Andrew Hare
+4  A: 

Try the following

myEnum = (TEnum)((object)value);
JaredPar