title: A way to parse .NET enum string or int value attributed with 'Flags'
body: <p>There is a nice way of figuring out the enumeration element using the following approach:</p>
  
  <pre><code>// memberType is enum type
  if (Enum.IsDefined(memberType, valueString))
  {
      return Enum.Parse(memberType, valueString);
  }
  else
  {
      try 
      {
          var underlyingValue = Convert.ChangeType(valueString, Enum.GetUnderlyingType(memberType));
          if (Enum.IsDefined(memberType, underlyingValue))
          {
              return underlyingValue;
          }
      }
      catch...
  }
  </code></pre>
  
  <p>This works like charm. Except for values built from enumerations marked with <code>FlagsAttribute</code>. For example, for this enum and a value:</p>
  
  <pre><code>[Flags]
  enum MyEnum {
      One = 0x1,
      Two = One &lt;&lt; 1,
      Four = One &lt;&lt; 2,
      Eight = One &lt;&lt; 3
  }
  
  var e = MyEnum.One | MyEnum.Eight;
  </code></pre>
  
  <p>the approach above doesn't work. Looks like the only way to make it work is to try to get all the enum values and bitwise AND them with the input value. That's somewhat tedious though. So do you know any better way?</p>
  
  <h2>Answer:</h2>
  
  <p>The final method looks like this:</p>
  
  <pre><code>var parsed = Enum.Parse(memberType, valueString);
  decimal d;
  if (!decimal.TryParse(parsed.ToString(), out d))
  {
      return parsed;
  }
  throw new ArgumentOutOfRangeException(memberInfo.Name, valueString, "Bad configuration parameter value.");
  </code></pre>