1

So I need to write a method that does a lookup. It needs to take an enum generic and then convert the enum value to a string and return it

This is what I have so far

public static object lookupColumn<TEnum>(int? id, string defaultValue="")
        where TEnum : struct, IConvertible
{
    if (!(typeof(TEnum).IsEnum))
        throw new ArgumentException("TEnum must be of type Enum");

    if (!id.HasValue)
        return defaultValue;

    TEnum enumValue = (TEnum) id.Value; //This line doesn't compile
    return enumValue.ToString();
}

Any suggestions?

EDIT: The part that is causing me trouble is casting the int to an enum

Mikhail D'Souza
  • 583
  • 1
  • 4
  • 9

1 Answers1

0

Why not use Enum.Parse instead of the direct cast? Call ToString on the value to convert.

Ricardo Peres
  • 13,724
  • 5
  • 57
  • 74
  • I didn't realize that the Enum.Parse method can accept the int AS A STRING. Should have read the documentation better. (http://msdn.microsoft.com/en-us/library/system.enum.parse(v=vs.110).aspx) – Mikhail D'Souza Dec 22 '14 at 09:20
  • You can also use Enum.GetName() or make your cast work by doing an intermediate cast to object `TEnum enumValue = (TEnum)(object)id.Value;` – Grax32 Dec 23 '14 at 15:42