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

Re: How to convert string to enum ? by Mountain

Mountain
Thu Dec 18 10:52:47 CST 2003

use the Parse() method of enum

"Christian Schwarz" <anonymous@systemtechnik-online.de> wrote in message
news:brslrg$74j7l$1@ID-57495.news.uni-berlin.de...
> 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
>
>



Re: How to convert string to enum ? by Christian

Christian
Thu Dec 18 10:57:50 CST 2003

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



Re: How to convert string to enum ? by Paul

Paul
Thu Dec 18 12:42:07 CST 2003

Try:

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

Paul


"Christian Schwarz" <anonymous@systemtechnik-online.de> wrote in message
news:brsm7r$73f8r$1@ID-57495.news.uni-berlin.de...
> 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
>
>