Quantcast
Channel: Odyssey to knowledge » C# Notes
Viewing all articles
Browse latest Browse all 4

Resolve Description from dynamic enum values

$
0
0

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 and another list of dynamic values. Therefore we can now do a match like below to obtain the dynamic description for dynamic enum values like below.

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 to ListItem for a dropbox in the webUi. I hated the ugly idea of iterating each of the items in a loop so the lambda again came to the rescue

ValueDropDown.Items.AddRange(enumHumanValues.Select( s => new ListItem(s)).ToArray());


Viewing all articles
Browse latest Browse all 4

Trending Articles