Converting raw data type to enumerated type

Posted by Jim Lahman on Geeks with Blogs See other posts from Geeks with Blogs or by Jim Lahman
Published on Thu, 03 Mar 2011 19:35:35 GMT Indexed on 2011/03/03 23:25 UTC
Read the original article Hit count: 304

Filed under:

There are times when an enumerated type is preferred over using the raw data type.  An example of using a scheme is when we need to check the health of x-ray gauges in use on a production line.  Rather than using a scheme like 0, 1 and 2, we can use an enumerated type:

   1:   /// <summary>
   2:   /// POR Healthy status indicator
   3:   /// </summary>
   4:   /// <remarks>The healthy status is for each POR x-ray gauge; each has its own status.</remarks>
   5:   [Flags]
   6:   public enum POR_HEALTH : short
   7:   {
   8:        /// <summary>
   9:        /// POR1 healthy status indicator
  10:        /// </summary>
  11:         POR1 = 0,        
  12:         /// <summary>
  13:         /// POR2 healthy status indicator
  14:         /// </summary>
  15:         POR2 = 1,        
  16:         /// <summary>
  17:         /// Both POR1 and POR2 healthy status indicator
  18:         /// </summary>
  19:         BOTH = 2         
  20:   }

By using the [Flags] attribute, we are treating the enumerated type as a bit mask.  We can then use bitwise operations such as AND, OR, NOT etc. .

Now, when we want to check the health of a specific gauge, we would rather use the name of the gauge than the numeric identity; it makes for better reading and programming practice.

To translate the numeric identity to the enumerated value, we use the Parse method of Enum class:

POR_HEALTH GaugeHealth = (POR_HEALTH) Enum.Parse(typeof(POR_HEALTH), XrayMsg.Gauge_ID.ToString());

The Parse method creates an instance of the enumerated type. 

Now, we can use the name of the gauge rather than the numeric identity:

   1:  if (GaugeHealth == POR_HEALTH.POR1 || GaugeHealth == POR_HEALTH.BOTH)
   2:  {
   3:         XrayHealthyTag.Name = Properties.Settings.Default.POR1XRayHealthyTag;
   4:  }
   5:  else if (GaugeHealth == POR_HEALTH.POR2)
   6:  {
   7:         XrayHealthyTag.Name = Properties.Settings.Default.POR2XRayHealthyTag;
   8:  }

© Geeks with Blogs or respective owner