0

i have an enum with custom attributes, something like:

public enum EnumStatus
{
    [CharValue('*')]
    Empty,

    [CharValue('A')]
    value1,

    [CharValue('P')]
    value2,
}

the "forward" way seems easy, coming with an enum value an getting the custom attribute using reflection, GetCustomAttributes and that like.

but i want some kind of reverse resolving. having an char value, i want to have an enum value to work with.

something like:

public static Enum GetEnumValue(this Enum source, char value)
{...}

which should return EnumStatus.value1, if i put an 'A' as value parameter.

any ideas? i do not want to make an extra hashtable, deferring the enums.

thank you so much!

Mare Infinitus
  • 8,024
  • 8
  • 64
  • 113

2 Answers2

1

from the example i made this here:

    public static T GetEnumValue<T, TExpected>(char value) where TExpected : Attribute
    {
        var type = typeof(T);

        if (type.IsEnum)
        {
            foreach (var field in type.GetFields())
            {
                dynamic attribute = Attribute.GetCustomAttribute(field,
                    typeof(TExpected)) as TExpected;

                if (attribute != null)
                {
                    if (attribute.Value == value)
                    {
                        return (T)field.GetValue(null);
                    }
                }
            }
        }

        return default(T);
    }

works great...

Termininja
  • 6,620
  • 12
  • 48
  • 49
Mare Infinitus
  • 8,024
  • 8
  • 64
  • 113
0

I'd recommend using the DescriptionAttribute and following the example here: https://stackoverflow.com/a/4367868/905651.

Community
  • 1
  • 1
weenoid
  • 1,156
  • 2
  • 11
  • 24
  • Thank you very much! The "default" description attribute is already in use. Therefore i need another way. But perhaps i can use that example. It doesn't need to be generic, but i need "generic" attributes. – Mare Infinitus Apr 13 '12 at 18:00
  • from the example i made this here: public static T GetEnum(char value) { var type = typeof(T); if (type.IsEnum) { foreach (var field in type.GetFields()) { var attribute = Attribute.GetCustomAttribute(field, typeof(CharValueAttribute)) as CharValueAttribute; if (attribute != null) { if (attribute.Value == value) return (T)field.GetValue(null); } } } return default(T); } – Mare Infinitus Apr 13 '12 at 18:50