Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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.



This post first appeared on Hugonne - Another .net Coding, please read the originial post: here

Share the post

Setting an enum value from a string

×

Subscribe to Hugonne - Another .net Coding

Get updates delivered right to your inbox!

Thank you for your subscription

×