How to convert string to enum ?

  • Thread starter Thread starter Christian Schwarz
  • Start date Start date
C

Christian Schwarz

Hello,

I know how to convert a member of an enumeration into a string:

enum MyEnum
{
FirstEnum = 0,
SecondEnum,
ThirdEnum
}

string myEnumReadable = MyEnum.SecondEnum.ToString();

"enumReadable" now contains "SecondEnum". But how would you convert it back
to MyEnum type ? The following line throws an InvalidCastException (most
probably because there's no FormatProvider to/from MyEnum type):

MyEnum myEnum = Convert.ChangeType(myEnumReadable, typeof(MyEnum),
System.Globalization.CultureInfo.CurrentCulture);

This conversion is needed for an object exporter/importer which saves/loades
all objects to/from strings. That's why I need to find a generally valid way
for converting strings back to their appropriate enumeration members. It
isn't feasible to implement a special conversion for each enumeration.

Greetings, Christian
 
Sorry, I forgot to mention that I program for Compact Framework.
Unfortunately there isn't a enum.Parse() method ...

Do you know another way ?

Greetings, Christian
 
Try:

MyEnum myEnum =
System.ComponentModel.TypeDescriptor.GetConverter(typeof(MyEnum)).ConvertFro
mString(str) as MyEnum;

Paul
 
Back
Top