21

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>();
    }
}
Matthias
  • 3,403
  • 8
  • 37
  • 50
  • Please do't prefix yur titles with "WinRT C#: " and such. That's what the tags are for. – John Saunders May 24 '12 at 06:15
  • Thats not possible. The Type.GetMember is still present in .Net 4.5! – logicnp May 24 '12 at 06:19
  • @logicnp: The WinRT API is a subset of the full .NET API. – Jon Skeet May 24 '12 at 06:23
  • No, it's not defined on the Type class in the System namespace. Configuration: Windows Consumer Preview, VS11 Beta, Assembly C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5\System.Runtime.dll – Matthias May 24 '12 at 06:24
  • @JonSkeet: My bad! However, except via Intellisense/compile-time errors, how does one know if a API is present in WinRT or not. The API documentation page http://msdn.microsoft.com/en-us/library/system.type.getmember%28v=vs.110%29.aspx does not have a filter for WinRT like it does for Silverlight. – logicnp May 24 '12 at 06:27
  • @logicnp: There's a separate set of documentation for WinRT at the moment, I believe. Whether they merge it into the main .NET documentation after release or not is a different matter. – Jon Skeet May 24 '12 at 06:30

1 Answers1

14

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.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900