0

I found c# does not allow generic type to be enum, so I did some research online and find this thread Anyone know a good workaround for the lack of an enum generic constraint?, then I installed the nuget package, but in my extension method, (T)x.ToInteger() throws can not convert type 'int' to 'T'. Thus GetDescription() won't work either, because it is my another enum extension method to get description of enum value. If I replace 'T' with a specified Enum, the following code will work. Any help is appreciated. Here is my extension methos:

public static string ToEnumDescription<T>(this string enumValue) 
    where T: struct, IEnumConstraint
{
    if (enumValue.IsNullOrEmpty()) return string.Empty;
    var list = enumValue.Split(',');
    var descriptionList = new List<String>();
    foreach (var x in list)
    {
        var description = (x.IsInteger() && Enum.IsDefined(typeof(T), x.ToInteger())) 
            ? ((T)x.ToInteger()).GetDescription() 
            : string.Empty;
        descriptionList.Add(description);
    }
    return descriptionList.ToCommaSeperatedNoQuote();
}
Community
  • 1
  • 1
Steven Zack
  • 4,984
  • 19
  • 57
  • 88

1 Answers1

2

As a workaround, instead of (T)x.ToInteger() you should be able to do: (T)(object)x.ToInteger().

This involves boxing and unboxing the value but that most likely is not a significant performance issue here.

Eren Ersönmez
  • 38,383
  • 7
  • 71
  • 92
  • Wonderful, now I can convert int to T, but 'T' must be convert into System.Enum before I can use GetDescription() extension method. – Steven Zack Mar 24 '17 at 21:23