How to convert string to enum ?

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
 
C

Christian Schwarz

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
 
P

Paul Wardle

Try:

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

Paul
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top