Enums can sure be confusing. I am trying to create an extension method on the Enum type that will take a value and return the names of all the bits that match.
Given:
[Flags]
public enum PlanetsEnum
{
Mercury=1,
Venus=2,
Earth=4,
Mars=8,
Jupiter=16,
//etc....
}
I would like to create an extension method that return a dictionary of only the selected values. So if:
PlanetsEnum neighbors = PlanetsEnum.Mars | PlanetEnum.Venus; //10
IDictionary dict = neighbors.ToDictionary();
foreach (KeyValuePair<String, Int32> kvp in dict)
{
Console.WriteLine(kvp.Key);
}
/*
* Should Print:
* Mars
* Venus
*/
I would expect to see Mars & Venus written to the console but I am instead seeing all the values of PlanetEnum. Here is my extension method code:
public static IDictionary<string, Int32> ToDictionary(this Enum enumeration)
{
Type type = enumeration.GetType();
return Enum.GetValues(type).Cast<Int32>().ToDictionary(field => Enum.GetName(type, field));
}
Does anyone see what I am doing wrong? I know that Enum.GetValues
is returning all fields of the enum type, how do I get it to only return fields of the enum instance?
Thanks a lot for any help,
Keith