Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Generic Type Restriction for Enums

0.00/5 (No votes)
10 Jul 2011 1  
How to restrict a generic type identifier to only allow enums

I was looking for a way to restrict a generic type identifier to only allow enums. Since you are not allowed to use where T : Enum, I checked the metadata for Enum and found that it implements ValueType, IComparable, IFormattable, IConvertible. You can't use ValueType as restriction, but struct works fine.

In other words, use “where T : struct, IComparable, IFormattable, IConvertible” to make a type restriction which should work well as an enum restriction.

The reason why I needed the specification is that I want to be able to fetch the DescriptionAttribute from enums. I use it to be able to add friendly names to enum values.

Example enum:

public enum MyEnum
{
    [Description("Some value"]
    SomeValue,

    [Description("Foo bar")]
    FooBar
}

Fetch value:

MyEnum value = MyEnum.FooBar;

// will display "Foo bar"
Console.WriteLine(value.GetDescription());

The extension method that does the magic:

public static string GetDescription<T>(this T instance)
    where T : struct, IConvertible, IFormattable, IComparable
{
    var type = typeof (T);
    var memberInfo = type.GetMember(instance.ToString())[0];

    var attribute = (DescriptionAttribute)memberInfo.GetCustomAttributes(
        typeof(DescriptionAttribute), false).FirstOrDefault();
    return attribute == null ? instance.ToString() : attribute.Description;
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here