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 60 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.
  • 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 Offline
      realJSOPR Offline
      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
          • 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

            S Offline
            S Offline
            Simon Allaeys
            wrote on last edited by
            #25

            Why all the fuss about "starting programming a long time ago before the many of the rest of us"? I've been programming for 2 years now, and I wrote the folowing code snippit about one year ago:

            public static bool TryParseEnum<TEnum>(int value, out TEnum result)
            {
              result = default(TEnum);
              var type = typeof (TEnum);
              if (!type.IsEnum) return false;
              try
              {
                result = (TEnum) Enum.ToObject(type, value);
                return true;
              }
              catch
              {
                return false;
              }
            }
            
            public static bool TryParseEnum<TEnum>(string value, out TEnum result)
            {
              result = default(TEnum);
              var type = typeof(TEnum);
              if (!type.IsEnum) return false;
              value = value.ToUpperInvariant();
              var names = Enum.GetNames(type);
              // Enum.IsDefined() is only available as case sensitive
              foreach (var name in names)
              {
                if (name.ToUpperInvariant() != value)
                  continue;
                result = (TEnum)Enum.Parse(type, value, true);
                return true;
              }
              return false;
            }
            

            Advantages of this code: - you know if parsing succeeded (while you can't know when returning default values) - case insensitive

            modified on Thursday, December 3, 2009 3:13 PM

            C 1 Reply Last reply
            0
            • S Simon Allaeys

              Why all the fuss about "starting programming a long time ago before the many of the rest of us"? I've been programming for 2 years now, and I wrote the folowing code snippit about one year ago:

              public static bool TryParseEnum<TEnum>(int value, out TEnum result)
              {
                result = default(TEnum);
                var type = typeof (TEnum);
                if (!type.IsEnum) return false;
                try
                {
                  result = (TEnum) Enum.ToObject(type, value);
                  return true;
                }
                catch
                {
                  return false;
                }
              }
              
              public static bool TryParseEnum<TEnum>(string value, out TEnum result)
              {
                result = default(TEnum);
                var type = typeof(TEnum);
                if (!type.IsEnum) return false;
                value = value.ToUpperInvariant();
                var names = Enum.GetNames(type);
                // Enum.IsDefined() is only available as case sensitive
                foreach (var name in names)
                {
                  if (name.ToUpperInvariant() != value)
                    continue;
                  result = (TEnum)Enum.Parse(type, value, true);
                  return true;
                }
                return false;
              }
              

              Advantages of this code: - you know if parsing succeeded (while you can't know when returning default values) - case insensitive

              modified on Thursday, December 3, 2009 3:13 PM

              C Offline
              C Offline
              ColinBashBash
              wrote on last edited by
              #26

              That seems like a real good idea. Of course, being a programmer, I immediately try to "perfect" it. My long winded code ends up looking like this. (i wish i could add it as a static method to the Enum class)... i'm also playing with delegates just so that i can play with delegates...

              public static class EnumExt {
              public static bool TryParse<T>(object value, out T outputEnum) {
              if (Enum.IsDefined(typeof(T), value)) {
              outputEnum = (T)value;
              return true;
              } else {
              outputEnum = default(T);
              return false;
              }
              }
              public static bool TryParse<T>(string value, out T outputEnum) {
              string find = Array.Find<string>(Enum.GetNames(typeof(T)),
              delegate(string s) { return String.Compare(s, value, true) == 0; });
              if (find != null) {
              outputEnum = (T)Enum.Parse(typeof(T), find);
              return true;
              } else {
              outputEnum = default(T);
              return false;
              }
              }
              }

              MyEnum example;
              if (EnumExt.TryParse<MyEnum>(1, out example)) {
              //do stuff
              } else {
              //do other stuff
              }

              S 1 Reply Last reply
              0
              • C ColinBashBash

                That seems like a real good idea. Of course, being a programmer, I immediately try to "perfect" it. My long winded code ends up looking like this. (i wish i could add it as a static method to the Enum class)... i'm also playing with delegates just so that i can play with delegates...

                public static class EnumExt {
                public static bool TryParse<T>(object value, out T outputEnum) {
                if (Enum.IsDefined(typeof(T), value)) {
                outputEnum = (T)value;
                return true;
                } else {
                outputEnum = default(T);
                return false;
                }
                }
                public static bool TryParse<T>(string value, out T outputEnum) {
                string find = Array.Find<string>(Enum.GetNames(typeof(T)),
                delegate(string s) { return String.Compare(s, value, true) == 0; });
                if (find != null) {
                outputEnum = (T)Enum.Parse(typeof(T), find);
                return true;
                } else {
                outputEnum = default(T);
                return false;
                }
                }
                }

                MyEnum example;
                if (EnumExt.TryParse<MyEnum>(1, out example)) {
                //do stuff
                } else {
                //do other stuff
                }

                S Offline
                S Offline
                Simon Allaeys
                wrote on last edited by
                #27

                While using these methods I found a shortcoming... there is no support for flags! So this is how I improved it:

                public static bool TryParseEnum(object value, out EnumType result)
                {
                result = default(EnumType);
                if (value == null) return false;
                var type = typeof (EnumType);
                if (!type.IsEnum) return false;
                int iValue;
                return Int32.TryParse(value.ToString(), out iValue)
                ? TryParseEnum(iValue, out result)
                : TryParseEnum(value.ToString(), out result);
                }

                public static bool TryParseEnum(int value, out EnumType result)
                {
                result = default(EnumType);
                var type = typeof(EnumType);
                if (!type.IsEnum) return false;
                result = (EnumType)Enum.Parse(type, value.ToString());
                // Verify if the result is valid,
                // Enum.Parse might just return the input value, while this is not a defined value of the enum
                if (result.ToString().Contains(", ") || Enum.IsDefined(type, result))
                return true;
                result = default(EnumType);
                return false;
                }

                public static bool TryParseEnum(string value, out EnumType result)
                {
                result = default(EnumType);
                if (string.IsNullOrEmpty(value)) return false;
                var type = typeof(EnumType);
                if (!type.IsEnum) return false;
                value = value.ToUpperInvariant();
                try
                {
                result = (EnumType)Enum.Parse(type, value, true);
                return true;
                }
                catch (ArgumentException)
                {
                return false;
                }
                }

                :edited: Edited the object method to use the two other methods, this should be more reliable for both normal enums and bit flag enums. Casting/parsing values which are non-numeric and non-string values is anyway not possible in .NET.

                modified on Wednesday, February 10, 2010 6:31 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