tisdag 10 juni 2014

Enum with DescriptionAttribute

public static class EnumExtensions
{
    public static T GetAttribute(this Enum enumeration) where T : Attribute
    {
        var type = enumeration.GetType();
        var memberInfos = type.GetMember(enumeration.ToString());
        var attribute = memberInfos[0].GetCustomAttributes(typeof (T), false);

        var attributes = attribute.Cast().ToList();
        
        return attributes.SingleOrDefault();
    }

    public static string Description(this Enum enumeration)
    {
        var attribute = GetAttribute(enumeration);
        if (attribute == null)
            return "";

        return attribute.Description;
    }
}

public enum GroundType
{
    [Description("Jord")]
    Soil = 1,
    [Description("Gräs")]
    Grass = 2
}

public class DescriptionAttribute : Attribute
{
    private readonly string _descr;

    public DescriptionAttribute(string descr) { _descr = descr; }

    public string Description
    {
        get { return _descr; }
    }

    public override string ToString() { return Description; }
}
Use like so:
var groundType = GroundType.Soil;
var desc = groundType.Description();

Inga kommentarer:

Skicka en kommentar