Rick van den Bosch - Blog

... on software development, architecture and more

Converting string to enumeration value

Questa posted a very usefull piece of code...
It's possible to convert a string representation of an enum back to an enum!

  private enum MyEnumeration
  {
      FooBar,
      Foo,
      Bar
  }

  ...

  MyEnum foo = MyEnum.Foo;
  string foobar = foo.ToString();
  MyEnum bar = (MyEnum)Enum.Parse(typeof(MyEnum), foobar);

At the end of this code, the variable 'bar' has the MyEnum value 'Foo', just the way it's supposed to be...

Comments

Puneet said:

Really helpful.

# January 16, 2008 10:23 AM

Marc D said:

Here's utilty function to wrap it:

public static T Parse<T>(string value) {

    return (T)Enum.Parse(typeof(T), value);

}

MyEnum foo = MyEnum.Foo;

string foobar = foo.ToString();

MyEnum bar = EnumHelper.Parse<MyEnum>, foobar);

# September 25, 2008 3:39 PM

gjaw said:

very good..really helpful

# November 22, 2008 11:09 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Please add 4 and 8 and type the answer here: