Create generic extension method with enumerations

I am fairly new to C# and I am trying to create a generic extension method that that takes any enumeration as the parameter. Based on the enumeration I want to retrieve an attribute that has been applied within the enumeration. I want to be able to use this extension method across multiple enumerations. I currently only have the static method directly in my class that contains the enumeration and it looks like this:

public static string GetIDForEnum(Enum enum)
{
    var item = typeof(Enum).GetMember(enum.ToString());
    var attr = item[0].GetCustomAttribute(typeof(DescriptionAttribute), false);
    if(attr.Length > 0)
       return ((DescriptionAttribute)attr[0]).Description;
    else
       return enum.ToString();
}

How do I make this a generic extension method?

Jon Skeet
people
quotationmark

How do I make this a generic extension method?

You can't, at the moment... because C# doesn't allow you to constrain a type parameter to derive from System.Enum. What you want is:

public static string GetIdForEnum<T>(T value) where T : Enum, struct

... but that constraint is invalid in C#.

However, it's not invalid in IL... which is why I created Unconstrained Melody. It's basically a mixture of:

  • A library with useful generic delegate and enum methods
  • A tool to run ildasm and ilasm to convert permitted constraints into the ones we really want

You could do something similar yourself - but it's all a bit hacky, to be honest. For enums it does allow an awful lot more efficient code though...

people

See more on this question at Stackoverflow