Question

public enum Values
{
    [Description("All Fabs")]
    value1 = 0,
    [Description("Fab 1")]
    value2 = 1,
    [Description("Fab 2")]
    value3 = 2,
    [Description("Fab 3")]
    value4 = 3,
    [Description("Fab 4")]
    value5 = 4,
    [Description("Fab 5")]
    value6 = 5           
}

public static Dictionary<int, string> ConvertEnumToDictionary<T>()
{
    var type = typeof(T);
    if(!type.IsEnum)
    {
        throw new InvalidOperationException();
    }
    Dictionary<int, string> result = new Dictionary<int, string>();
    bool header = true;
    foreach(var field in type.GetFields())
    {
        if(header)
        {
            header = false;
            continue;
        }
        var attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
        if(attribute != null)
        {
            result.Add((int)field.GetValue(null), attribute.Description);
        }
    }
    return result;
}

Displays.ConvertEnumToDictionary<Values>().Where(i => (i.Key == value2 || i.Key == value1));

the above line produces diff results in development environment and in staging environment.

In development it returns both the values but in staging sometimes it returns one value only (either value1 or value2) and sometimes both.

Please help me find out the problem here.

Was it helpful?

Solution

It may be because of this sentence in the documentation:

Your code must not depend on the order in which fields are returned, because that order varies.

You're skipping the first item you iterate (your header variable). That will only work if the fields come back in the same order every time.

Try removing the code that skips the "header", and instead getting the field value into a variable and checking whether value.Equals(default(T)). That would skip the enum value with 0 as its backing integer value.

OTHER TIPS

It may be linked to the "header" part while iterating raw fields. Prefer this manner to iterate thru enum values:

FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Static)

Then you can start at offset-0:

for (int i = 0; i < fields.Length; i++)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top