System.ComponentModel.DescriptionAttribute in portable class library

Crudler picture Crudler · Sep 20, 2013 · Viewed 10.4k times · Source

I am using the Description attribute in my enums to provide a user friendly name to an enum field. e.g.

public enum InstallationType
{
    [Description("Forward of Bulk Head")]
    FORWARD = 0,

    [Description("Rear of Bulk Head")]
    REAR = 1,

    [Description("Roof Mounted")]
    ROOF = 2,
}

And accessing this is easy with a nice helper method:

public static string GetDescriptionFromEnumValue(Enum value)
    {
        DescriptionAttribute attribute = value.GetType()
            .GetField(value.ToString())
            .GetCustomAttributes(typeof(DescriptionAttribute), false)
            .SingleOrDefault() as DescriptionAttribute;
        return attribute == null ? value.ToString() : attribute.Description;
    }

I need to convert this into a portable class library but it doesn't seem to have access to the System.ComponentModel library. when I try add a reverence VS tells me that I have referenced everything already.

Thanks

Answer

Jehof picture Jehof · Sep 20, 2013

Since DescriptionAttribute is not available for portable class libraries you need to use another attribute. The namespace System.ComponentModel.DataAnnotations which is available for portable class libraries provides the attribute DisplayAttribute that you can use instead.

public enum InstallationType
{
    [Display(Description="Forward of Bulk Head")]
    FORWARD = 0,

    [Display(Description="Rear of Bulk Head")]
    REAR = 1,

    [Display(Description="Roof Mounted")]
    ROOF = 2,
}

Your method needs to be changed to

public static string GetDescriptionFromEnumValue(Enum value)
    {
        DisplayAttribute attribute = value.GetType()
            .GetField(value.ToString())
            .GetCustomAttributes(typeof(DisplayAttribute ), false)
            .SingleOrDefault() as DisplayAttribute ;
        return attribute == null ? value.ToString() : attribute.Description;
    }