Yogesh Jagota's Personal Blog
small c# code snippets and free code libraries

Extension function to check for valid enum values

Thursday, 31 January 2008 22:07 by Yogesh Jagota

If you set a enum to a int value, you can use this function to test the value to be correct or not. What is special about this function is that if you use the Flags attribute for the enum, it will check if the value is a right bit wise match.

   1:  /// <summary>
   2:  /// Checks whether a enum value is correct or not
   3:  /// </summary>
   4:  /// <param name="enumerator">Enumerator on which
   5:  /// extension method is used</param>
   6:  /// <returns>returns true if valid, false
   7:  /// otherwise</returns>
   8:  public static bool IsValid(this Enum enumerator)
   9:  {
  10:      bool defined = Enum.IsDefined(enumerator.GetType(), enumerator);
  11:   
  12:      if (!defined)
  13:      {
  14:          FlagsAttribute[] attributes =
  15:              (FlagsAttribute[])enumerator.GetType().GetCustomAttributes(
  16:              typeof(FlagsAttribute), false);
  17:   
  18:          // If the value is a right bitwise match and
  19:          // FlagsAttribute is uses, ToString returns 
  20:          // all values seperated with commas.
  21:          if (attributes != null && attributes.Length > 0)
  22:              return enumerator.ToString().Contains(",");
  23:      }
  24:   
  25:      return defined;
  26:  }

This can better be understood with the example provided.

   1:  public enum NonFlagEnum
   2:  {
   3:      One = 1,
   4:      Two = 2,
   5:      Three = 4,
   6:      Four = 8,
   7:      Five = 16
   8:  }
   9:   
  10:  [Flags]
  11:  public enum FlagEnum
  12:  {
  13:      One = 1,
  14:      Two = 2,
  15:      Three = 4,
  16:      Four = 8,
  17:      Five = 16,
  18:  }
  19:   
  20:  // Non flaged
  21:  NonFlagEnum nfe = NonFlagEnum.One;
  22:  nfe.IsValid(); // true
  23:   
  24:  nfe = (NonFlagEnum) 5;
  25:  nfe.IsValid(); // false
  26:   
  27:  nfe = (NonFlagEnum) 21;
  28:  nfe.IsValid(); // false
  29:   
  30:  nfe = (NonFlagEnum) 32;
  31:  nfe.IsValid(); // false
  32:   
  33:  nfe = NonFlagEnum.One | NonFlagEnum.Four;
  34:  nfe.IsValid(); // false because 9 is not present in the enum
  35:   
  36:  // Flaged
  37:  FlagEnum fe = FlagEnum.One;
  38:  fe.IsValid(); // true
  39:   
  40:  fe = (FlagEnum) 5;
  41:  // true because value will be FlagEnum.One | FlagEnum.Three
  42:  fe.IsValid();
  43:   
  44:  fe = (FlagEnum) 21;
  45:  // true because value will be: 
  46:  // FlagEnum.Five | FlagEnum.Three | FlagEnum.One
  47:  fe.IsValid();
  48:   
  49:  fe = (FlagEnum) 32;
  50:  fe.IsValid(); // false
  51:   
  52:  fe = FlagEnum.One | FlagEnum.Four;
  53:  fe.IsValid(); // true
  54:  

Del.icio.usDigg It!DZone It!kick it on DotNetKicks.com
Tags:   ,
Categories:   C# | General
Actions:   E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

Add comment


 

biuquote
Loading