Search code examples
c#reflectionattributesenumsgetcustomattributes

How to reverse resolve custom attributes?


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!


Solution

  • 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...