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();
}
0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Wonderful, now I can convert int to T, but 'T' must be convert into System.Enum before I can use GetDescription() extension method.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.