Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Enum and generics

Enum and generics

Scheduled Pinned Locked Moved C#
csharphelpquestionhtmlcom
24 Posts 5 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • N Offline
    N Offline
    N a v a n e e t h
    wrote on last edited by
    #1

    I have a generic method which looks for a specific attribute and returns value of "Text" property. My attribute is named "DetailsAttribute". Here is my generic method

    public static string GetDescription<EnumType>(EnumType enumType) {

    string description = string.Empty;
    
    Type type = enumType.GetType();
    if (type != null) {
       // Getting filed info
        FieldInfo info = type.GetField(enumType.ToString());
        if (info != null) {
            // getting the attributes
              DetailsAttribute\[\] attributes = info.GetCustomAttributes(typeof(DetailsAttribute), false)  as DetailsAttribute\[\];
              if (attributes != null && attributes.Length > 0)
                  description = attributes\[0\].Text;
        }
    }
    return description;
    

    }

    This works fine. But I am looking for applying a constraint to the generic parameter "enumType" which should allow only enum types. I am not able to write something like

    public static string GetDescription<EnumType>(EnumType enumType) : where enumType : enum // error

    How can I set such kind of restriction ? Also is there any better method than what I provided to retrieve attribute values from fields ? any help would be appreciated.

    All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

    L X P S 5 Replies Last reply
    0
    • N N a v a n e e t h

      I have a generic method which looks for a specific attribute and returns value of "Text" property. My attribute is named "DetailsAttribute". Here is my generic method

      public static string GetDescription<EnumType>(EnumType enumType) {

      string description = string.Empty;
      
      Type type = enumType.GetType();
      if (type != null) {
         // Getting filed info
          FieldInfo info = type.GetField(enumType.ToString());
          if (info != null) {
              // getting the attributes
                DetailsAttribute\[\] attributes = info.GetCustomAttributes(typeof(DetailsAttribute), false)  as DetailsAttribute\[\];
                if (attributes != null && attributes.Length > 0)
                    description = attributes\[0\].Text;
          }
      }
      return description;
      

      }

      This works fine. But I am looking for applying a constraint to the generic parameter "enumType" which should allow only enum types. I am not able to write something like

      public static string GetDescription<EnumType>(EnumType enumType) : where enumType : enum // error

      How can I set such kind of restriction ? Also is there any better method than what I provided to retrieve attribute values from fields ? any help would be appreciated.

      All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

      L Offline
      L Offline
      leppie
      wrote on last edited by
      #2

      N a v a n e e t h wrote:

      How can I set such kind of restriction ?

      You cant. Best will be to have where EnumType : struct and have a check inside the method.

      xacc.ide - now with TabsToSpaces support
      IronScheme - 1.0 alpha 4a out now (29 May 2008)

      N 1 Reply Last reply
      0
      • N N a v a n e e t h

        I have a generic method which looks for a specific attribute and returns value of "Text" property. My attribute is named "DetailsAttribute". Here is my generic method

        public static string GetDescription<EnumType>(EnumType enumType) {

        string description = string.Empty;
        
        Type type = enumType.GetType();
        if (type != null) {
           // Getting filed info
            FieldInfo info = type.GetField(enumType.ToString());
            if (info != null) {
                // getting the attributes
                  DetailsAttribute\[\] attributes = info.GetCustomAttributes(typeof(DetailsAttribute), false)  as DetailsAttribute\[\];
                  if (attributes != null && attributes.Length > 0)
                      description = attributes\[0\].Text;
            }
        }
        return description;
        

        }

        This works fine. But I am looking for applying a constraint to the generic parameter "enumType" which should allow only enum types. I am not able to write something like

        public static string GetDescription<EnumType>(EnumType enumType) : where enumType : enum // error

        How can I set such kind of restriction ? Also is there any better method than what I provided to retrieve attribute values from fields ? any help would be appreciated.

        All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

        X Offline
        X Offline
        xibeifeijian
        wrote on last edited by
        #3

        Maybe you should check it by yourself. Just like this: public static string GetDescription(EnumType enumType) { string description = string.Empty; Type type = enumType.GetType(); Type typParent=type.BaseType; bool blIsEnum=false; while(typParent!=null) { if(typParent==typeof(System.Enum)) { blIsEnum=true; break; } typParent=typParent.BaseType; } if(blIsEnum==false) { throw new Exception("Haha,game over!^_^"); } ......

        :^):^):^):^):^):^):^):^):^):^):^):^) :^):rose::rose::rose::rose::rose:¦¦?¦?¦¦ :^):rose::^):^):^):^)¦?????¦ :^):rose::^):^):^):^)¦¦?¦?¦¦ :^):rose::^):^):^):^)¦?????¦ :^):rose::rose::rose::rose::rose:¦¦?¦?¦¦ :^):^):^):^):^):^):^):^):^):^):^):^)

        N 1 Reply Last reply
        0
        • L leppie

          N a v a n e e t h wrote:

          How can I set such kind of restriction ?

          You cant. Best will be to have where EnumType : struct and have a check inside the method.

          xacc.ide - now with TabsToSpaces support
          IronScheme - 1.0 alpha 4a out now (29 May 2008)

          N Offline
          N Offline
          N a v a n e e t h
          wrote on last edited by
          #4

          Yeah, I guessed it. Thanks leppie. Do you think there is any better method to take the attribute value other than what I did ?

          All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

          1 Reply Last reply
          0
          • X xibeifeijian

            Maybe you should check it by yourself. Just like this: public static string GetDescription(EnumType enumType) { string description = string.Empty; Type type = enumType.GetType(); Type typParent=type.BaseType; bool blIsEnum=false; while(typParent!=null) { if(typParent==typeof(System.Enum)) { blIsEnum=true; break; } typParent=typParent.BaseType; } if(blIsEnum==false) { throw new Exception("Haha,game over!^_^"); } ......

            :^):^):^):^):^):^):^):^):^):^):^):^) :^):rose::rose::rose::rose::rose:¦¦?¦?¦¦ :^):rose::^):^):^):^)¦?????¦ :^):rose::^):^):^):^)¦¦?¦?¦¦ :^):rose::^):^):^):^)¦?????¦ :^):rose::rose::rose::rose::rose:¦¦?¦?¦¦ :^):^):^):^):^):^):^):^):^):^):^):^)

            N Offline
            N Offline
            N a v a n e e t h
            wrote on last edited by
            #5

            Thanks.

            xibeifeijian wrote:

            Type type = enumType.GetType(); Type typParent=type.BaseType; bool blIsEnum=false; while(typParent!=null)

            Why not make it simple like

            if (enumType.GetType() != typeof(System.Enum))
            throw new InvalidOperationException("An enum is expected");

            or am I missing something ?

            All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

            X L 2 Replies Last reply
            0
            • N N a v a n e e t h

              Thanks.

              xibeifeijian wrote:

              Type type = enumType.GetType(); Type typParent=type.BaseType; bool blIsEnum=false; while(typParent!=null)

              Why not make it simple like

              if (enumType.GetType() != typeof(System.Enum))
              throw new InvalidOperationException("An enum is expected");

              or am I missing something ?

              All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

              X Offline
              X Offline
              xibeifeijian
              wrote on last edited by
              #6

              Ha,Sorry,my error. As the enum type cann't inherit,so you can judge it in this way: if (enumType.GetType().BaseType != typeof(System.Enum)) You must use basetype to judge them,because the son type won't equals the parent type.System.Enum is a root type for all the enum types.

              :^):^):^):^):^):^):^):^):^):^):^):^) :^):rose::rose::rose::rose::rose:¦¦?¦?¦¦ :^):rose::^):^):^):^)¦?????¦ :^):rose::^):^):^):^)¦¦?¦?¦¦ :^):rose::^):^):^):^)¦?????¦ :^):rose::rose::rose::rose::rose:¦¦?¦?¦¦ :^):^):^):^):^):^):^):^):^):^):^):^)

              N 1 Reply Last reply
              0
              • N N a v a n e e t h

                Thanks.

                xibeifeijian wrote:

                Type type = enumType.GetType(); Type typParent=type.BaseType; bool blIsEnum=false; while(typParent!=null)

                Why not make it simple like

                if (enumType.GetType() != typeof(System.Enum))
                throw new InvalidOperationException("An enum is expected");

                or am I missing something ?

                All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

                L Offline
                L Offline
                leppie
                wrote on last edited by
                #7

                How about: enumType is Enum ... :doh: You guys certainly like to do things the hard way! ;P

                xacc.ide - now with TabsToSpaces support
                IronScheme - 1.0 alpha 4a out now (29 May 2008)

                N 1 Reply Last reply
                0
                • X xibeifeijian

                  Ha,Sorry,my error. As the enum type cann't inherit,so you can judge it in this way: if (enumType.GetType().BaseType != typeof(System.Enum)) You must use basetype to judge them,because the son type won't equals the parent type.System.Enum is a root type for all the enum types.

                  :^):^):^):^):^):^):^):^):^):^):^):^) :^):rose::rose::rose::rose::rose:¦¦?¦?¦¦ :^):rose::^):^):^):^)¦?????¦ :^):rose::^):^):^):^)¦¦?¦?¦¦ :^):rose::^):^):^):^)¦?????¦ :^):rose::rose::rose::rose::rose:¦¦?¦?¦¦ :^):^):^):^):^):^):^):^):^):^):^):^)

                  N Offline
                  N Offline
                  N a v a n e e t h
                  wrote on last edited by
                  #8

                  Ya.. BaseType is required. Thanks :)

                  All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

                  1 Reply Last reply
                  0
                  • L leppie

                    How about: enumType is Enum ... :doh: You guys certainly like to do things the hard way! ;P

                    xacc.ide - now with TabsToSpaces support
                    IronScheme - 1.0 alpha 4a out now (29 May 2008)

                    N Offline
                    N Offline
                    N a v a n e e t h
                    wrote on last edited by
                    #9

                    leppie wrote:

                    enumType is Enum

                    Looks simple, but I cannot make it working. AFAIK, BaseType checking is required. When you use is, it throws exception for enum types too.

                    All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

                    L 1 Reply Last reply
                    0
                    • N N a v a n e e t h

                      leppie wrote:

                      enumType is Enum

                      Looks simple, but I cannot make it working. AFAIK, BaseType checking is required. When you use is, it throws exception for enum types too.

                      All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

                      L Offline
                      L Offline
                      leppie
                      wrote on last edited by
                      #10

                      N a v a n e e t h wrote:

                      Looks simple, but I cannot make it working. AFAIK, BaseType checking is required. When you use is, it throws exception for enum types too.

                      Then you are doing something wrong! The following prints 'Friday':

                      object f = DayOfWeek.Friday;

                      if (f is Enum)
                      {
                      Console.WriteLine(f);
                      }
                      else
                      {
                      Console.WriteLine("Not enum");
                      }

                      xacc.ide - now with TabsToSpaces support
                      IronScheme - 1.0 alpha 4a out now (29 May 2008)

                      1 Reply Last reply
                      0
                      • N N a v a n e e t h

                        I have a generic method which looks for a specific attribute and returns value of "Text" property. My attribute is named "DetailsAttribute". Here is my generic method

                        public static string GetDescription<EnumType>(EnumType enumType) {

                        string description = string.Empty;
                        
                        Type type = enumType.GetType();
                        if (type != null) {
                           // Getting filed info
                            FieldInfo info = type.GetField(enumType.ToString());
                            if (info != null) {
                                // getting the attributes
                                  DetailsAttribute\[\] attributes = info.GetCustomAttributes(typeof(DetailsAttribute), false)  as DetailsAttribute\[\];
                                  if (attributes != null && attributes.Length > 0)
                                      description = attributes\[0\].Text;
                            }
                        }
                        return description;
                        

                        }

                        This works fine. But I am looking for applying a constraint to the generic parameter "enumType" which should allow only enum types. I am not able to write something like

                        public static string GetDescription<EnumType>(EnumType enumType) : where enumType : enum // error

                        How can I set such kind of restriction ? Also is there any better method than what I provided to retrieve attribute values from fields ? any help would be appreciated.

                        All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

                        P Offline
                        P Offline
                        PIEBALDconsult
                        wrote on last edited by
                        #11

                        Does no one read my articles? :~ I use:

                        System.Type basetype = typeof(T) ;

                        if ( !basetype.IsEnum )
                        {
                        throw ( new System.ArgumentException ( "T must be an Enum" ) ) ;
                        }

                        I suspect that all that checking for null in your example is needless. And please read this[^].

                        X N S 3 Replies Last reply
                        0
                        • P PIEBALDconsult

                          Does no one read my articles? :~ I use:

                          System.Type basetype = typeof(T) ;

                          if ( !basetype.IsEnum )
                          {
                          throw ( new System.ArgumentException ( "T must be an Enum" ) ) ;
                          }

                          I suspect that all that checking for null in your example is needless. And please read this[^].

                          X Offline
                          X Offline
                          xibeifeijian
                          wrote on last edited by
                          #12

                          Haha ,this is the best way ! :)

                          :^):^):^):^):^):^):^):^):^):^):^):^) :^):rose::rose::rose::rose::rose:¦¦?¦?¦¦ :^):rose::^):^):^):^)¦?????¦ :^):rose::^):^):^):^)¦¦?¦?¦¦ :^):rose::^):^):^):^)¦?????¦ :^):rose::rose::rose::rose::rose:¦¦?¦?¦¦ :^):^):^):^):^):^):^):^):^):^):^):^)

                          1 Reply Last reply
                          0
                          • P PIEBALDconsult

                            Does no one read my articles? :~ I use:

                            System.Type basetype = typeof(T) ;

                            if ( !basetype.IsEnum )
                            {
                            throw ( new System.ArgumentException ( "T must be an Enum" ) ) ;
                            }

                            I suspect that all that checking for null in your example is needless. And please read this[^].

                            N Offline
                            N Offline
                            N a v a n e e t h
                            wrote on last edited by
                            #13

                            PIEBALDconsult wrote:

                            Does no one read my articles?

                            Sorry, I just missed it.

                            PIEBALDconsult wrote:

                            I suspect that all that checking for null in your example is needless.

                            I am not getting you fully. Are you saying that the methods I used to get "FieldInfo", attributes will never return NULL ?

                            All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

                            P 1 Reply Last reply
                            0
                            • N N a v a n e e t h

                              I have a generic method which looks for a specific attribute and returns value of "Text" property. My attribute is named "DetailsAttribute". Here is my generic method

                              public static string GetDescription<EnumType>(EnumType enumType) {

                              string description = string.Empty;
                              
                              Type type = enumType.GetType();
                              if (type != null) {
                                 // Getting filed info
                                  FieldInfo info = type.GetField(enumType.ToString());
                                  if (info != null) {
                                      // getting the attributes
                                        DetailsAttribute\[\] attributes = info.GetCustomAttributes(typeof(DetailsAttribute), false)  as DetailsAttribute\[\];
                                        if (attributes != null && attributes.Length > 0)
                                            description = attributes\[0\].Text;
                                  }
                              }
                              return description;
                              

                              }

                              This works fine. But I am looking for applying a constraint to the generic parameter "enumType" which should allow only enum types. I am not able to write something like

                              public static string GetDescription<EnumType>(EnumType enumType) : where enumType : enum // error

                              How can I set such kind of restriction ? Also is there any better method than what I provided to retrieve attribute values from fields ? any help would be appreciated.

                              All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

                              S Offline
                              S Offline
                              Scott Dorman
                              wrote on last edited by
                              #14

                              You can't apply a generic constraint on an enum type. The best you can get is struct. Also, take a look at this article[^] for a way to work with enums and a description attribute.

                              Scott Dorman

                              Microsoft® MVP - Visual C# | MCPD President - Tampa Bay IASA [Blog][Articles][Forum Guidelines]


                              Hey, hey, hey. Don't be mean. We don't have to be mean because, remember, no matter where you go, there you are. - Buckaroo Banzai

                              N 1 Reply Last reply
                              0
                              • P PIEBALDconsult

                                Does no one read my articles? :~ I use:

                                System.Type basetype = typeof(T) ;

                                if ( !basetype.IsEnum )
                                {
                                throw ( new System.ArgumentException ( "T must be an Enum" ) ) ;
                                }

                                I suspect that all that checking for null in your example is needless. And please read this[^].

                                S Offline
                                S Offline
                                Scott Dorman
                                wrote on last edited by
                                #15

                                PIEBALDconsult wrote:

                                Does no one read my articles?

                                Hmmm...I missed that one somehow. Interesting approach to things. Did you see my article[^]? I have a similar GetDescription method.

                                Scott Dorman

                                Microsoft® MVP - Visual C# | MCPD President - Tampa Bay IASA [Blog][Articles][Forum Guidelines]


                                Hey, hey, hey. Don't be mean. We don't have to be mean because, remember, no matter where you go, there you are. - Buckaroo Banzai

                                P 1 Reply Last reply
                                0
                                • N N a v a n e e t h

                                  PIEBALDconsult wrote:

                                  Does no one read my articles?

                                  Sorry, I just missed it.

                                  PIEBALDconsult wrote:

                                  I suspect that all that checking for null in your example is needless.

                                  I am not getting you fully. Are you saying that the methods I used to get "FieldInfo", attributes will never return NULL ?

                                  All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

                                  P Offline
                                  P Offline
                                  PIEBALDconsult
                                  wrote on last edited by
                                  #16

                                  Correct. GetType() won't and GetCustomAttributes won't, GetField won't because you're passing in a known field name (in this case).

                                  modified on Tuesday, July 8, 2008 12:41 AM

                                  N 1 Reply Last reply
                                  0
                                  • S Scott Dorman

                                    PIEBALDconsult wrote:

                                    Does no one read my articles?

                                    Hmmm...I missed that one somehow. Interesting approach to things. Did you see my article[^]? I have a similar GetDescription method.

                                    Scott Dorman

                                    Microsoft® MVP - Visual C# | MCPD President - Tampa Bay IASA [Blog][Articles][Forum Guidelines]


                                    Hey, hey, hey. Don't be mean. We don't have to be mean because, remember, no matter where you go, there you are. - Buckaroo Banzai

                                    P Offline
                                    P Offline
                                    PIEBALDconsult
                                    wrote on last edited by
                                    #17

                                    I probably did, I definitely remember the picture of someone blocking the Green Monster.

                                    1 Reply Last reply
                                    0
                                    • N N a v a n e e t h

                                      I have a generic method which looks for a specific attribute and returns value of "Text" property. My attribute is named "DetailsAttribute". Here is my generic method

                                      public static string GetDescription<EnumType>(EnumType enumType) {

                                      string description = string.Empty;
                                      
                                      Type type = enumType.GetType();
                                      if (type != null) {
                                         // Getting filed info
                                          FieldInfo info = type.GetField(enumType.ToString());
                                          if (info != null) {
                                              // getting the attributes
                                                DetailsAttribute\[\] attributes = info.GetCustomAttributes(typeof(DetailsAttribute), false)  as DetailsAttribute\[\];
                                                if (attributes != null && attributes.Length > 0)
                                                    description = attributes\[0\].Text;
                                          }
                                      }
                                      return description;
                                      

                                      }

                                      This works fine. But I am looking for applying a constraint to the generic parameter "enumType" which should allow only enum types. I am not able to write something like

                                      public static string GetDescription<EnumType>(EnumType enumType) : where enumType : enum // error

                                      How can I set such kind of restriction ? Also is there any better method than what I provided to retrieve attribute values from fields ? any help would be appreciated.

                                      All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

                                      P Offline
                                      P Offline
                                      PIEBALDconsult
                                      wrote on last edited by
                                      #18

                                      Oh, and... a few months ago I asked about it on MSDN and Jon Skeet said he'd ask whether or not an enum constraint might be in the future, he later reported... "maybe". I suspect there are a lot more important things concerning them. I think maybe we should start a letter campaign.

                                      N 1 Reply Last reply
                                      0
                                      • P PIEBALDconsult

                                        Correct. GetType() won't and GetCustomAttributes won't, GetField won't because you're passing in a known field name (in this case).

                                        modified on Tuesday, July 8, 2008 12:41 AM

                                        N Offline
                                        N Offline
                                        N a v a n e e t h
                                        wrote on last edited by
                                        #19

                                        Thanks. I will remove the NULL checking. Thanks

                                        All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

                                        1 Reply Last reply
                                        0
                                        • S Scott Dorman

                                          You can't apply a generic constraint on an enum type. The best you can get is struct. Also, take a look at this article[^] for a way to work with enums and a description attribute.

                                          Scott Dorman

                                          Microsoft® MVP - Visual C# | MCPD President - Tampa Bay IASA [Blog][Articles][Forum Guidelines]


                                          Hey, hey, hey. Don't be mean. We don't have to be mean because, remember, no matter where you go, there you are. - Buckaroo Banzai

                                          N Offline
                                          N Offline
                                          N a v a n e e t h
                                          wrote on last edited by
                                          #20

                                          Scott, Thanks. I figured it out. Great article though

                                          All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

                                          S 1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups