0

I was looking for a way to get an alternate value from an enum, and referenced this answer

https://stackoverflow.com/a/10986749/5122089

Here it uses a description attribute to assign a value and then a method for extracting that as so

public static string DescriptionAttr<T>(this T source) {
   FieldInfo fi = source.GetType().GetField(source.ToString());

    DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(
        typeof(DescriptionAttribute), false);

    if (attributes != null && attributes.Length > 0) return attributes[0].Description;
else return source.ToString(); }

Only I'm unfortunately stuck in the dark ages with .net 3.5 Compact Framework, and do not appear to have access to System.ComponentModel.DescriptionAttribute

Might anyone give me a hint how to get something like this working...

Community
  • 1
  • 1
axa
  • 428
  • 6
  • 19

1 Answers1

1

I'm not sure this is what you're looking for. I just did some changes on the original code:

static class MyClass
{
    public static string DescriptionAttr<T>(this T source, Type attrType, string propertyName)
    {
        FieldInfo fi = source.GetType().GetField(source.ToString());

        var attributes = fi.GetCustomAttributes(attrType, false);

        if (attributes != null && attributes.Length > 0)
        {
            var propertyInfo = attributes[0].GetType().GetProperty(propertyName);

            if (propertyInfo != null)
            {
                var value = propertyInfo.GetValue(attributes[0], null);
                return value as string;
            }
        }
        else
            return source.ToString();

        return null;
    }
}

public enum MyEnum
{
    Name1 = 1,
    [MyAttribute("Here is another")]
    HereIsAnother = 2,
    [MyAttribute("Last one")]
    LastOne = 3
}

class MyAttribute : Attribute
{
    public string Description { get; set; }

    public MyAttribute(string desc)
    {
        Description = desc;
    }
}

Usage:

var x = MyEnum.HereIsAnother.DescriptionAttr(typeof(MyAttribute), "Description");
user1845593
  • 1,736
  • 3
  • 20
  • 37
  • Indeed this gets me exactly what I'm looking for. I very much appreciate you taking the time to demonstrate. – axa May 04 '17 at 14:56
  • the attributes[0] isn't elegant to have there. You might want to change that somehow or not. Mark the question as valid, please – user1845593 May 04 '17 at 15:43
  • indeed I have refactor​ed the answer greatly but it has enlightened me on how to apply custom attributes as well as reflect and dig out information. I thought I'd let it sit a bit and see what others come up with – axa May 05 '17 at 04:36