Enum to dictionary

Well, you're trying to use a variable of type Type as a generic type argument. You can't do that with generics, which are about compile-time types.

You can do it with reflection, but it would be better to make it a generic method. Unfortunately you can't constrain a generic type parameter to be an enum, although I have some hacks to work around that in Unconstrained Melody.

Failing that, you could use just a struct type constraint for a generic method which would be a good start.

Now, the next problem is that you're trying to get a Dictionary<int, string> - but the values of an enum aren't int values. They might be convertable to int values, but they aren't there immediately. You could use Convert.ToInt32 to do that, but you would have to do something.

Finally (for the moment) what would you expect to happen with an enum using a uint or long underlying type?


Jon Skeet has written everything you need ;)

But here you have your code that is working:

public static Dictionary<int, string> ToDictionary(this Enum @enum)
{
  var type = @enum.GetType();
  return Enum.GetValues(type).Cast<int>().ToDictionary(e => e, e => Enum.GetName(type, e));
}

Tags:

C#

.Net