1

I have the following 2 methods in my code that basically turn an enum into a dictionay of ints and strings:

  public Dictionary<int, string> GetChannelLevels()
    {
        IEnumerable<ChannelLevel> enumValues = Enum.GetValues(typeof(ChannelLevel)).Cast<ChannelLevel>();

        var channelLevels = enumValues.ToDictionary(value => (int)value, value => value.ToString());

        return channelLevels;
    }


    public Dictionary<int, string> GetCategoryLevels()
    {
        IEnumerable<CategoryLevel> enumValues = Enum.GetValues(typeof(CategoryLevel)).Cast<CategoryLevel>();

        var channelLevels = enumValues.ToDictionary(value => (int)value, value => value.ToString());

        return channelLevels;
    }

Since the code of these 2 methods is basically the same, I thought of writing a generic method which would look something like this:

private Dictionary<int, string> GetEnumDictionary<T>() where T : struct, IConvertible 
    {
        if (!typeof(T).IsEnum)
        {
            throw new ArgumentException("T must be an enumerated type");
        }



        IEnumerable<T> enumValues = Enum.GetValues(typeof(T)).Cast<T>();

        var channelLevels = enumValues.ToDictionary(value => /*THIS IS WHERE THE PROBLEM IS*/  (int)value, value => value.ToString());

        return channelLevels;

    }

The problem is that since C# doesn't have a generic enum constaints the method cann't recognize T as an enum and therefore I cann't convery in to int.

How can I solve this problem without writing a new function altogether?

Shai Aharoni
  • 1,955
  • 13
  • 25

1 Answers1

0

Like @thmshd suggested i replaced the explicit int casting with Convert.ToInt32 and it seems to solve the problem. So the final version of the method is:

private Dictionary<int, string> GetEnumDictionary<T>() where T : struct, IConvertible 
{
    if (!typeof(T).IsEnum)
    {
        throw new ArgumentException("T must be an enumerated type");
    }

    IEnumerable<T> enumValues = Enum.GetValues(typeof(T)).Cast<T>();

    var enumDictionary = enumValues.ToDictionary(value => Convert.ToInt32(value), value => value.ToString());

    return enumDictionary;
}
Shai Aharoni
  • 1,955
  • 13
  • 25