Question

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!

Was it helpful?

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top