I was today stuck with the dilemma for making changes to a bottom level library which depended on types defined on top level libraries. The intention of the generic code at the bottom layer was well defined and as such it did not reference any concrete top level types.
But in that case how can I get the description of a dynamic enum type form its value without having the static information of the top level type in the lower library ?
So I rather decided to do resolve this dilemma using a simple match expression. That’s the end task. But lets understand in steps.
1)It is possible to obtain the FieldInfo for a Type anyway like below
FieldInfo [] fieldInfos = dynamicType.GetFields(BindingFlags.Public | BindingFlags.Static);
2)Now that I have the fieldInfos , I can for a dynamic enum Type create a dictionary of the filed description and its value like below
var enumDescValuePairs = fieldinfo.UnboxedType.GetFields(BindingFlags.Public |BindingFlags.Static) .Select( kv => new KeyValuePair<string,string>( kv.Name.ToString(CultureInfo.InvariantCulture), ((ulong)Convert.ChangeType(kv.GetValue(null), typeof (ulong))).ToString(CultureInfo.InvariantCulture))) .ToDictionary( kvp => kvp.Key , kvp => kvp.Value);
3) Now we have a dictionary of all possible
var enumHumanValues = (from v in values join dvp in enumDescValuePairs on v.ToString() equals dvp.Value select dvp.Key).ToArray();
4) A subtle unrelated to the topic but interesting issue. I cannot implicitly cast a generic list
ValueDropDown.Items.AddRange(enumHumanValues.Select( s => new ListItem(s)).ToArray());