.NET 4.5 WinRT: Get custom attributes from enum value

Currently I’m very busy in creating a bigger Windows 8 Metro app for managing private financial data. I’m creating the app with the WinRT/.NET 4.5/C#/XAML programming model of Windows 8 and my first experiences are good. Of course, in the Windows Consumer Preview and VS11 Beta there are some nasty bugs when creating apps, but altogether it’s quite nice.

Now, .NET developers of Windows 8 Metro apps are facing the problem, that there are many API changes for the WinRT bits of .NET and to cope with those. Yesterday I was facing a nasty problem: I wanted to get a custom attribute, that’s defined on an enum value like those:

public enum AssetType
{
    [Display(Name="Single share")]
    Share,

    [Display(Name="Fonds")]
    Fonds
}

Now, in „normal“ .NET it’s possible to retrieve a custom attribute on an enum value with the following little helper:

public static class EnumHelper
{
    public static T GetAttribute(this Enum enumValue)
        where T : Attribute
    {
        return enumValue
            .GetType()
            .GetMember(enumValue.ToString())[0]
            .GetCustomAttribute<T>();
    }
}

So that’s pretty easy. But wait: the GetMember() isn’t available on .NET 4.5 for WinRT. Meeeeeep! But fortunately there’s a solution. In .NET WinRT the Type class has a GetTypeInfo() extension method, which gives an instance of the TypeInfo class for this type. And finally TypeInfo has many handy helper methods for retrieving type information, e.g. the declared properties and methods. For retrieving information of an enum value, in .NET WinRT we can call the GetDeclaredField() method to get a FieldInfo instance of the enum value. Then on this we can call GetCustomAttribute<T>():

public static class EnumHelper
{
    public static T GetAttribute(this Enum enumValue)
        where T : Attribute
    {
        return enumValue
            .GetType()
            .GetTypeInfo()
            .GetDeclaredField(enumValue.ToString())
            .GetCustomAttribute<T>();
    }
}

So in conclusion I think while there are many new and changed APIs to learn for Metro style apps, in the end the whole platform is highly functional and usable. You just have to know where to find this functionality 😉

kick it on DotNetKicks.com