2009-10-14

Setting an enum value from a string

In a piece of code I was reviewing I saw that they wanted to set the value for an enum from a string, and what they did was to create a large method with a big switch statement, setting the correct enum value for each case. Something like:

  1: enum Operators
  2: {
  3:    GreaterThan,
  4:    Equals,
  5:    LessThan
  6: }
  7: 
  8: Operators GetOperatorFromString(string s)
  9: {
 10:    switch(s.ToUpper())
 11:    {
 12:       case "GREATERTHAN":
 13:          return Operators.GreaterThan;
 14:       case "EQUALS":
 15:          return Operators.Equals;
 16:       case "LESSTHAN":
 17:          return Operators.LessThan;
 18:    }
 19: }

Now, this could be kind of simple if your enum doesn’t have many values, but if we’re talking about very large lists, then we have a problem…

Well, the solution for this is actually very simple, by using System.Enum.Parse, which has the following signature:

object Enum.Parse(System.Type enumType, string value, bool ignoreCase);

So, you can write the following:

  1: enum Operators
  2: {
  3:    GreaterThan,
  4:    Equals,
  5:    LessThan
  6: }
  7: 
  8: // ...
  9: 
 10: Operators o = (Operators)Enum.Parse(typeof(Operators), "greaterthan", true);

Notice that, since we have the ingnoreCase parameter set to true,  we can use the string in any kind of case. If the string value doesn’t match any of the enum values, an exception of type ArgumentException will be raised.

1 comentario:

Your tips and thoughts are always welcome, and they provide good motivation: