2

How to iterate on enum and get Attribute & Values?

public enum TableName {
    [DescriptionWithValue("offline", "create table offline (uid int, date datetime, id int)")]
    Offline,
    [Description("Online","create table online (uid int, date datetime, id int)")]
    online,
    [Description("Amount","create table amount (uid int, date datetime, id int)")]
    amount
}
James Z
  • 12,209
  • 10
  • 24
  • 44
Joseph Cenk
  • 107
  • 1
  • 1
  • 7
  • 1
    What did you try to do it? SO is about fixing _your_ Code - not implementing your ideas. Please go over [how to ask](https://stackoverflow.com/help/how-to-ask) and [on-topic](https://stackoverflow.com/help/on-topic) again and if you have questions provide your code as [mvce](https://stackoverflow.com/help/mcve). If you encounter errors, copy and paste the error message verbatim ( word for word) into your question. Avoid using screenshots unless you need to convey layout errors. We can NOT copy and paste your image into our IDEs to fix your code. – Patrick Artner Feb 18 '18 at 12:34
  • 1
    [Attributes](https://stackoverflow.com/questions/1799370/getting-attributes-of-enums-value), and [iterate](https://stackoverflow.com/questions/105372/how-do-i-enumerate-an-enum) . I used a search engine. – Crowcoder Feb 18 '18 at 12:37
  • @PatrickArtner This is a programming problem. – Joseph Cenk Feb 18 '18 at 12:38
  • 2
    What @PatrickArtner means is for you to show what you have tried to do. How you've tried to implement that and where you are getting stumped or what error message is getting displayed when you try. It will be possible from there to point you in the right direction or fix the code as opposed to getting someone to write it for you from scratch. – Fabulous Feb 18 '18 at 12:42

1 Answers1

1

You mean like this?

    class Program
    {
        static void Main()
        {
            foreach (var field in typeof(TableName).GetFields(BindingFlags.Static | BindingFlags.Public))
            {
                ProcessField(field);
            }
        }

        static void ProcessField(FieldInfo field)
        {
            ProcessD(field.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute);
            ProcessDWV(field.GetCustomAttribute(typeof(DescriptionWithValueAttribute)) as DescriptionWithValueAttribute);            
        }

        static void ProcessD(DescriptionAttribute attribute)
        {
            if(attribute != null)
            {
                //...
            }
        }

        static void ProcessDWV(DescriptionWithValueAttribute attribute)
        {
            if (attribute != null)
            {
                //...
            }
        }
Dee J. Doena
  • 1,631
  • 3
  • 16
  • 26