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. Other Discussions
  3. Clever Code
  4. Enumerators

Enumerators

Scheduled Pinned Locked Moved Clever Code
jsonhelpquestion
27 Posts 13 Posters 7 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.
  • L Lost User

    John Simmons / outlaw programmer wrote:

    I started programming long before many of the rest of you.

    I first programmed on this actual system[^] using machine code, fed in from the buttons on the front panel, or boot-loaded from paper tape; great fun!

    C Offline
    C Offline
    Chris Meech
    wrote on last edited by
    #5

    Actually I've inferred the age of that machine from the grainy black and white photos. :)

    Chris Meech I am Canadian. [heard in a local bar] In theory there is no difference between theory and practice. In practice there is. [Yogi Berra]

    L 1 Reply Last reply
    0
    • C Chris Meech

      Actually I've inferred the age of that machine from the grainy black and white photos. :)

      Chris Meech I am Canadian. [heard in a local bar] In theory there is no difference between theory and practice. In practice there is. [Yogi Berra]

      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #6

      Chris Meech wrote:

      I've inferred the age of that machine from the grainy black and white photos.

      To say nothing of the dress sense of those of us in the computer room. The pictures were taken round about 1965 and although I am not in any of them, I do remember the names of a few of my colleagues that are pictured.

      1 Reply Last reply
      0
      • realJSOPR realJSOP

        In the spirit of the new charter of this forum - "wicked code" - I see this as wicked code... I started programming long before many of the rest of you. Over the years, I've grown to have a huge distrust of not only users and their antics, but also other programmers and their seeming apathy regarding ensuring that data is valid before trying to use it. One of the problems I encountered was storing and retrieving enumerator values in data sources, and preparing the code to gracefully handle manually values - either modified by the user, or incorrectly set or interpreted by the programmer. So I came up with this method that I have include i pretty much every program I write:

        	public static T IntToEnum<T>(int value, T defaultValue)
        	{
        		T enumValue = (Enum.IsDefined(typeof(T), value)) ? (T)(object)value : defaultValue;
        		return enumValue;
        	}
        

        The purpose of the method is to allow the programmer to initialize a data member of a specified enumerator type to a value contained in the ordinal list. The problem this method addresses is that if the programmer retrieves an enum ordinal value as an int type, and wants to initialize an enum data member, he really has no programmatic idea if the value represents a valid ordinal. He simply tries to set it, and hope for the best (handling an exception if the assignment goes sideways on him). This method allows the programmer to make the same attempt, but with controlled results and thereby avoiding the inevitable exception generated when an invalid ordinal value is used. Usage goes something like this:

        enum SomeEnum { Zero=0, Five=5, Six=6, Eight=8 };

        // this will result in the correct expected value - SomeEnum.Five
        SomeEnum value = IntToEnum(5, SomeEnum.Zero);

        // this will result in SomeEnum.Zero because the value (4) isn't a valid ordinal in the enumerator
        value = IntToEnum(4, SomeEnum.Zero);

        .45 ACP - because shooting twice is just silly
        -----
        "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
        -----
        "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001

        A Offline
        A Offline
        Andrew Rissing
        wrote on last edited by
        #7

        You could apply generics to this as well to reduce how many times you have to create this in your code. :D

            public static U ToEnum<T, U>(T value, U defaultValue)
            {
                return (Enum.IsDefined(typeof(U), value)) ? (U)((object)value) : defaultValue;
            }
        

        And made into an extension method, if you so choose.

        P 1 Reply Last reply
        0
        • A Andrew Rissing

          You could apply generics to this as well to reduce how many times you have to create this in your code. :D

              public static U ToEnum<T, U>(T value, U defaultValue)
              {
                  return (Enum.IsDefined(typeof(U), value)) ? (U)((object)value) : defaultValue;
              }
          

          And made into an extension method, if you so choose.

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

          What's the point of type T? You might as well just use object and remove the unnecessary cast. Personally, I would also eliminate the repeated typeof(U) and cache the Type, but that's just me.

          A 1 Reply Last reply
          0
          • P PIEBALDconsult

            What's the point of type T? You might as well just use object and remove the unnecessary cast. Personally, I would also eliminate the repeated typeof(U) and cache the Type, but that's just me.

            A Offline
            A Offline
            Andrew Rissing
            wrote on last edited by
            #9

            True, you could just drop that. I just got generic happy. As for caching the typeof(U), since that is going to change per method instance - I don't know if you'd get anything by caching that. Plus, I'm not sure how you'd simply do that without adding a bit of overhead to the whole process. Typeof would be done at compile time, so it should be fairly efficient as is.

            P 1 Reply Last reply
            0
            • A Andrew Rissing

              True, you could just drop that. I just got generic happy. As for caching the typeof(U), since that is going to change per method instance - I don't know if you'd get anything by caching that. Plus, I'm not sure how you'd simply do that without adding a bit of overhead to the whole process. Typeof would be done at compile time, so it should be fairly efficient as is.

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

              Oh, right, this is a method, not a class; I usually write a generic class and cache the Type.

              L 1 Reply Last reply
              0
              • realJSOPR realJSOP

                In the spirit of the new charter of this forum - "wicked code" - I see this as wicked code... I started programming long before many of the rest of you. Over the years, I've grown to have a huge distrust of not only users and their antics, but also other programmers and their seeming apathy regarding ensuring that data is valid before trying to use it. One of the problems I encountered was storing and retrieving enumerator values in data sources, and preparing the code to gracefully handle manually values - either modified by the user, or incorrectly set or interpreted by the programmer. So I came up with this method that I have include i pretty much every program I write:

                	public static T IntToEnum<T>(int value, T defaultValue)
                	{
                		T enumValue = (Enum.IsDefined(typeof(T), value)) ? (T)(object)value : defaultValue;
                		return enumValue;
                	}
                

                The purpose of the method is to allow the programmer to initialize a data member of a specified enumerator type to a value contained in the ordinal list. The problem this method addresses is that if the programmer retrieves an enum ordinal value as an int type, and wants to initialize an enum data member, he really has no programmatic idea if the value represents a valid ordinal. He simply tries to set it, and hope for the best (handling an exception if the assignment goes sideways on him). This method allows the programmer to make the same attempt, but with controlled results and thereby avoiding the inevitable exception generated when an invalid ordinal value is used. Usage goes something like this:

                enum SomeEnum { Zero=0, Five=5, Six=6, Eight=8 };

                // this will result in the correct expected value - SomeEnum.Five
                SomeEnum value = IntToEnum(5, SomeEnum.Zero);

                // this will result in SomeEnum.Zero because the value (4) isn't a valid ordinal in the enumerator
                value = IntToEnum(4, SomeEnum.Zero);

                .45 ACP - because shooting twice is just silly
                -----
                "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                -----
                "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001

                G Offline
                G Offline
                Graham Parkings
                wrote on last edited by
                #11

                Nice. but, personally, i would replace the default parameter with a delegate.

                realJSOPR 2 Replies Last reply
                0
                • G Graham Parkings

                  Nice. but, personally, i would replace the default parameter with a delegate.

                  realJSOPR Online
                  realJSOPR Online
                  realJSOP
                  wrote on last edited by
                  #12

                  But why? The whole purpose of the default parameter is to force the method to return a valid ordinal instead of throwing an exception. Making it a take a delegate would, IMHO, add unnecessary obfuscation and maintenance issues.

                  .45 ACP - because shooting twice is just silly
                  -----
                  "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                  -----
                  "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001

                  P 1 Reply Last reply
                  0
                  • P PIEBALDconsult

                    Oh, right, this is a method, not a class; I usually write a generic class and cache the Type.

                    L Offline
                    L Offline
                    longnights
                    wrote on last edited by
                    #13

                    I am interested in the caching concept... Can you give us a small sample on how its implemented. Do you write two blocks of code, like a singleton - where you save a reference to the type and return it every other time... I am not entirely sure how its done... please share :^)

                    P 1 Reply Last reply
                    0
                    • L longnights

                      I am interested in the caching concept... Can you give us a small sample on how its implemented. Do you write two blocks of code, like a singleton - where you save a reference to the type and return it every other time... I am not entirely sure how its done... please share :^)

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

                      Singleton schmingleton; static classes are what Singletons hope to be when they grow up. I hold a static reference to the Type; see here[^].

                      1 Reply Last reply
                      0
                      • realJSOPR realJSOP

                        But why? The whole purpose of the default parameter is to force the method to return a valid ordinal instead of throwing an exception. Making it a take a delegate would, IMHO, add unnecessary obfuscation and maintenance issues.

                        .45 ACP - because shooting twice is just silly
                        -----
                        "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                        -----
                        "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001

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

                        John Simmons / outlaw programmer wrote:

                        return a valid ordinal

                        Which you can't actually guarantee/enforce...

                        realJSOPR 1 Reply Last reply
                        0
                        • realJSOPR realJSOP

                          In the spirit of the new charter of this forum - "wicked code" - I see this as wicked code... I started programming long before many of the rest of you. Over the years, I've grown to have a huge distrust of not only users and their antics, but also other programmers and their seeming apathy regarding ensuring that data is valid before trying to use it. One of the problems I encountered was storing and retrieving enumerator values in data sources, and preparing the code to gracefully handle manually values - either modified by the user, or incorrectly set or interpreted by the programmer. So I came up with this method that I have include i pretty much every program I write:

                          	public static T IntToEnum<T>(int value, T defaultValue)
                          	{
                          		T enumValue = (Enum.IsDefined(typeof(T), value)) ? (T)(object)value : defaultValue;
                          		return enumValue;
                          	}
                          

                          The purpose of the method is to allow the programmer to initialize a data member of a specified enumerator type to a value contained in the ordinal list. The problem this method addresses is that if the programmer retrieves an enum ordinal value as an int type, and wants to initialize an enum data member, he really has no programmatic idea if the value represents a valid ordinal. He simply tries to set it, and hope for the best (handling an exception if the assignment goes sideways on him). This method allows the programmer to make the same attempt, but with controlled results and thereby avoiding the inevitable exception generated when an invalid ordinal value is used. Usage goes something like this:

                          enum SomeEnum { Zero=0, Five=5, Six=6, Eight=8 };

                          // this will result in the correct expected value - SomeEnum.Five
                          SomeEnum value = IntToEnum(5, SomeEnum.Zero);

                          // this will result in SomeEnum.Zero because the value (4) isn't a valid ordinal in the enumerator
                          value = IntToEnum(4, SomeEnum.Zero);

                          .45 ACP - because shooting twice is just silly
                          -----
                          "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                          -----
                          "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001

                          A Offline
                          A Offline
                          AECAEC
                          wrote on last edited by
                          #16

                          Nice View of the LEO. My First Machine (beyound the accounting machines) was the Wrirlwind I per 1960. My First real Job was on it's child The Mighty AN/FSQ-7 (Sage) Then its child the AN/FSQ-32A The only computer that had an official certified plumber (it was water cooled) on the IBM maintenance roster. Calling them in on the weekends was a trial. They would sihg songs from the IBM Song Book. Ugh! Yes the IBM Song Book - I still have a copy. If you want to see it Google for it. :) :)

                          1 Reply Last reply
                          0
                          • P PIEBALDconsult

                            John Simmons / outlaw programmer wrote:

                            return a valid ordinal

                            Which you can't actually guarantee/enforce...

                            realJSOPR Online
                            realJSOPR Online
                            realJSOP
                            wrote on last edited by
                            #17

                            How do you figure? If you pass in a default parameter of a given enum type (in our case, SomeEnum.Zero), then the ordinal has to exist in order to even pass a valid parameter (otherwise, the code wouldn't even compile).

                            .45 ACP - because shooting twice is just silly
                            -----
                            "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                            -----
                            "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001

                            P 1 Reply Last reply
                            0
                            • G Graham Parkings

                              Nice. but, personally, i would replace the default parameter with a delegate.

                              realJSOPR Online
                              realJSOPR Online
                              realJSOP
                              wrote on last edited by
                              #18

                              Just so you know, I didn't 1-vote your message...

                              .45 ACP - because shooting twice is just silly
                              -----
                              "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                              -----
                              "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001

                              1 Reply Last reply
                              0
                              • realJSOPR realJSOP

                                How do you figure? If you pass in a default parameter of a given enum type (in our case, SomeEnum.Zero), then the ordinal has to exist in order to even pass a valid parameter (otherwise, the code wouldn't even compile).

                                .45 ACP - because shooting twice is just silly
                                -----
                                "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                                -----
                                "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001

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

                                I could still send in default(T) or any other value. You could check it, but what will you do if the value isn't that of one of the members? Your code has to work for bit-mapped enumerations too doesn't it?

                                realJSOPR 1 Reply Last reply
                                0
                                • P PIEBALDconsult

                                  I could still send in default(T) or any other value. You could check it, but what will you do if the value isn't that of one of the members? Your code has to work for bit-mapped enumerations too doesn't it?

                                  realJSOPR Online
                                  realJSOPR Online
                                  realJSOP
                                  wrote on last edited by
                                  #20

                                  At some point, you have to rely on the programmer to know wtf he's doing. :) The name of the method kinda gives away its intended use.

                                  .45 ACP - because shooting twice is just silly
                                  -----
                                  "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                                  -----
                                  "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001

                                  modified on Saturday, November 21, 2009 9:22 AM

                                  1 Reply Last reply
                                  0
                                  • realJSOPR realJSOP

                                    In the spirit of the new charter of this forum - "wicked code" - I see this as wicked code... I started programming long before many of the rest of you. Over the years, I've grown to have a huge distrust of not only users and their antics, but also other programmers and their seeming apathy regarding ensuring that data is valid before trying to use it. One of the problems I encountered was storing and retrieving enumerator values in data sources, and preparing the code to gracefully handle manually values - either modified by the user, or incorrectly set or interpreted by the programmer. So I came up with this method that I have include i pretty much every program I write:

                                    	public static T IntToEnum<T>(int value, T defaultValue)
                                    	{
                                    		T enumValue = (Enum.IsDefined(typeof(T), value)) ? (T)(object)value : defaultValue;
                                    		return enumValue;
                                    	}
                                    

                                    The purpose of the method is to allow the programmer to initialize a data member of a specified enumerator type to a value contained in the ordinal list. The problem this method addresses is that if the programmer retrieves an enum ordinal value as an int type, and wants to initialize an enum data member, he really has no programmatic idea if the value represents a valid ordinal. He simply tries to set it, and hope for the best (handling an exception if the assignment goes sideways on him). This method allows the programmer to make the same attempt, but with controlled results and thereby avoiding the inevitable exception generated when an invalid ordinal value is used. Usage goes something like this:

                                    enum SomeEnum { Zero=0, Five=5, Six=6, Eight=8 };

                                    // this will result in the correct expected value - SomeEnum.Five
                                    SomeEnum value = IntToEnum(5, SomeEnum.Zero);

                                    // this will result in SomeEnum.Zero because the value (4) isn't a valid ordinal in the enumerator
                                    value = IntToEnum(4, SomeEnum.Zero);

                                    .45 ACP - because shooting twice is just silly
                                    -----
                                    "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                                    -----
                                    "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001

                                    P Offline
                                    P Offline
                                    Phil Martin
                                    wrote on last edited by
                                    #21

                                    Have you got that code handy in VB.Net? It might come in handy for you in the next few months. :) Tee hee hee.

                                    realJSOPR 1 Reply Last reply
                                    0
                                    • P Phil Martin

                                      Have you got that code handy in VB.Net? It might come in handy for you in the next few months. :) Tee hee hee.

                                      realJSOPR Online
                                      realJSOPR Online
                                      realJSOP
                                      wrote on last edited by
                                      #22

                                      That's okay - kick a guy when he's down... Do they even have enumerators in VB?

                                      .45 ACP - because shooting twice is just silly
                                      -----
                                      "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                                      -----
                                      "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001

                                      T 1 Reply Last reply
                                      0
                                      • realJSOPR realJSOP

                                        That's okay - kick a guy when he's down... Do they even have enumerators in VB?

                                        .45 ACP - because shooting twice is just silly
                                        -----
                                        "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                                        -----
                                        "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001

                                        T Offline
                                        T Offline
                                        Tom Deketelaere
                                        wrote on last edited by
                                        #23

                                        John Simmons / outlaw programmer wrote:

                                        Do they even have enumerators in VB?

                                        Euhm yes ;P

                                        John Simmons / outlaw programmer wrote:

                                        That's okay - kick a guy when he's down...

                                        Don't worry after a couple years you don't even feel the kicks anymore :sigh: ;P

                                        1 Reply Last reply
                                        0
                                        • realJSOPR realJSOP

                                          In the spirit of the new charter of this forum - "wicked code" - I see this as wicked code... I started programming long before many of the rest of you. Over the years, I've grown to have a huge distrust of not only users and their antics, but also other programmers and their seeming apathy regarding ensuring that data is valid before trying to use it. One of the problems I encountered was storing and retrieving enumerator values in data sources, and preparing the code to gracefully handle manually values - either modified by the user, or incorrectly set or interpreted by the programmer. So I came up with this method that I have include i pretty much every program I write:

                                          	public static T IntToEnum<T>(int value, T defaultValue)
                                          	{
                                          		T enumValue = (Enum.IsDefined(typeof(T), value)) ? (T)(object)value : defaultValue;
                                          		return enumValue;
                                          	}
                                          

                                          The purpose of the method is to allow the programmer to initialize a data member of a specified enumerator type to a value contained in the ordinal list. The problem this method addresses is that if the programmer retrieves an enum ordinal value as an int type, and wants to initialize an enum data member, he really has no programmatic idea if the value represents a valid ordinal. He simply tries to set it, and hope for the best (handling an exception if the assignment goes sideways on him). This method allows the programmer to make the same attempt, but with controlled results and thereby avoiding the inevitable exception generated when an invalid ordinal value is used. Usage goes something like this:

                                          enum SomeEnum { Zero=0, Five=5, Six=6, Eight=8 };

                                          // this will result in the correct expected value - SomeEnum.Five
                                          SomeEnum value = IntToEnum(5, SomeEnum.Zero);

                                          // this will result in SomeEnum.Zero because the value (4) isn't a valid ordinal in the enumerator
                                          value = IntToEnum(4, SomeEnum.Zero);

                                          .45 ACP - because shooting twice is just silly
                                          -----
                                          "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                                          -----
                                          "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001

                                          D Offline
                                          D Offline
                                          dojohansen
                                          wrote on last edited by
                                          #24

                                          I think I would prefer this

                                          public static bool TryGetEnumValue<T>(object value, out T enumValue)
                                          {
                                          bool defined = Enum.IsDefined(typeof(T), value);
                                          enumValue = (defined ? (T)value : default(T));
                                          return defined;
                                          }

                                          with usage

                                          SomeEnum v;
                                          if (!TryGetEnumValue(4, out v))
                                          throw new ...
                                          else
                                          ...

                                          The advantage is that this always tells you if the value is defined or not. With the original you'd get the value passed as "defaultValue" if the value tested is the default value OR if the value tested doesn't exist. Most of the time that doesn't really make sense - if the tested value is an argument from a caller for instance, the caller's intention might have been something quite different from using whatever enum member you've designated as the default.

                                          modified on Tuesday, December 1, 2009 4:03 AM

                                          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