Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get custom attributes of enum value [duplicate]

Tags:

In a WinRT .NET application (C#) I want to get the custom attributes, that are defined on an enum value. Take the following enum for example:

public enum MyEnum
{
    [Display(Name="Foo")]
    EnumValue1,

    [Display(Name="Bar")]
    EnumValue2
}

Now in "normal" .NET I know that I'm able to obtain the custom attributes of an enum value with enumValue.GetType().GetMember(enumValue.ToString()).

Unfortunately, in WinRT .NET the GetMember() method isn't available on the Type class.
Any suggestions how to go with this?

=====================================================

Thanks to Marc below, I found the answer! The following code works to get a specific custom attribute from an enum value in .NET 4.5 WinRT:

public static class EnumHelper
{
    public static T GetAttribute<T>(this Enum enumValue)
        where T : Attribute
    {
        return enumValue
            .GetType()
            .GetTypeInfo()
            .GetDeclaredField(enumValue.ToString())
            .GetCustomAttribute<T>();
    }
}
like image 252
Matthias Avatar asked May 24 '12 06:05

Matthias


People also ask

Can enum have duplicate values?

Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.

How do I find enum attributes?

Enum. GetValues(typeof(FunkyAttributesEnum)); foreach (int value in values) Tuple. Value = Enum. GetName(typeof(FunkyAttributesEnum), value);

Can enum have attributes?

An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden).

Do enum values have to be unique?

Show activity on this post. I also found the same idea on this question: Two enums have some elements in common, why does this produce an error? Enum names are in global scope, they need to be unique.


1 Answers

Rather than looking for members, you should perhaps look specifically for fields. If that isn't available on the Type in WinRT, add using System.Reflection; and use type.GetTypeInfo() and look on there too, as various reflection facets are moved to the type-info.

like image 162
Marc Gravell Avatar answered Oct 28 '22 05:10

Marc Gravell