2

Possible Duplicate:
Get Enum from Description attribute

I have an Enum that uses the descriptions attribute. I want to be able to set on objects -> property value based on a string passed in. If the string matches the one of the enum values description then that value should be chosen. Is it possible for me to this without using a lengthy for loop?

public enum Rule
{
     ....
     [Description("New Seed")]
     Rule2 = 2,
     ....
}

what I'm hoping for is something like

var object = new oject{ rule = Rule.Where(r=> r.description == rulestring)}
Community
  • 1
  • 1
Antarr Byrd
  • 24,863
  • 33
  • 100
  • 188
  • 1
    You can't do that, attributes are meta-data not real data (ie. not actual values). I simulate stuff like this with my own `StringValueAttribute` and some extensions methods, but there are limitations on that and you have to wire up the supporting infrastructure. – CodingGorilla Jun 08 '12 at 20:19
  • 1
    @CodingGorilla I don't understand what you mean. Enumerating over the enum values, and finding the one with a specific description shouldn't be hard. – CodesInChaos Jun 08 '12 at 20:21
  • @CodeInChaos He wants to treat the `Description` attribute as a member of the `Rule` enum, you can't do that. What I do is use some extension methods on the `Enum` type that extracts the attribute (in my case I call it `StringValueAttribute`) meta data and returns it. Which isn't all that hard, it's just different than what he's asking for. And it can get a little tricky because you are extending the `Enum` type rather than a specific implenentation of `Enum`. – CodingGorilla Jun 08 '12 at 20:29

1 Answers1

2
        Rule f;
        var type = typeof(Rule);
        foreach (var field in type.GetFields())
        {
            var attribute = Attribute.GetCustomAttribute(field,
                typeof(DescriptionAttribute)) as DescriptionAttribute;
            if (attribute != null)
            {
                if (attribute.Description == "description"){
                    f = (Rule)field.GetValue(null);
                break;}
            }
            else
            {
                if (field.Name == "description"){
                    f = (Rule)field.GetValue(null);
                break;}
            }
        } 

ref: Get Enum from Description attribute

Community
  • 1
  • 1
Matan Shahar
  • 3,190
  • 2
  • 20
  • 45
  • 3
    The link is in fact an exact duplicate. – Servy Jun 08 '12 at 20:28
  • 2
    Yes, I just write in this form for convenience. – Matan Shahar Jun 08 '12 at 20:31
  • 4
    Since it's an exact duplicate the thread should be closed accordingly, although I now see you don't have sufficient rep to vote-close. In the future, if you see an exact duplicate you can just comment with a link saying it's an exact duplicate rather than re-posting the same answer to a duplicate question. – Servy Jun 08 '12 at 20:32
  • 2
    Just trying to help, but I'll keep it in mind... – Matan Shahar Jun 08 '12 at 20:35