www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - String to enum

reply useo <useo6 start.bg> writes:
Hi,

does anyone know how I can cast a string to an enum which also
contains strings? For example:

enum MyENUM : string {

x = "123"
y = "456"
z = "789"

}

...

string myString = X;
to!(MyENUM)(myString); //  Error: cannot implicitly convert
expression (_adDupT((& D12TypeInfo_Aya6__initZ),s)) of char[]...
cast(MyENUM) myString; // Does work, but it seems that other values
like MyENUM.a, MyENUM.b... are also successfully casted to MyENUM but
MyENUM doesn't contain a, b or similiar invalid/undefined values.

I hope anyone can solve the problem... thanks.
Dec 10 2010
parent Jesse Phillips <jessekphillips+D gmail.com> writes:
useo Wrote:

 Hi,
 
 does anyone know how I can cast a string to an enum which also
 contains strings? For example:
 
 enum MyENUM : string {
 
 x = "123"
 y = "456"
 z = "789"
 
 }
 
 ...
 
 string myString = X;
 to!(MyENUM)(myString); //  Error: cannot implicitly convert
 expression (_adDupT((& D12TypeInfo_Aya6__initZ),s)) of char[]...
 cast(MyENUM) myString; // Does work, but it seems that other values
 like MyENUM.a, MyENUM.b... are also successfully casted to MyENUM but
 MyENUM doesn't contain a, b or similiar invalid/undefined values.
 
 I hope anyone can solve the problem... thanks.
You should get a compiler error for using MyENUM.b if it doesn't exist. Casting is the correct way to do conversion, but as you are aware this doesn't guarantee that it is within the Enum. You can use a switch statement and throw an exception in the default. I am looking at ways to improve to! such that it can do more and is safer than cast. After the new year I'll probably have more time to look at building my proposed changes and I think this is a good one to add to the list.
Dec 10 2010