Can I check if a value is convertible to a valid value of an enum?

Nicholas Wilson via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Sep 24 20:20:23 PDT 2015


On Friday, 25 September 2015 at 03:12:20 UTC, French Football 
wrote:
> ...without having to loop over the enum?
>
> enum SomeType : string { CHEESE = "cheese", POTATO = "potato" }
> string valid_value = "cheese";
> string invalid_value = "pizza";
>
> bool test( string value ){
>     if( value.isConvertableToSomeType ){ // this be the magic I 
> seek
>         //do something
>         return true;
>     }
>     return false;
> }
>
> void main(){
>     writeln( test( valid_value ) ); //prints true
>     writeln( test( invalid_value ) ); //prints false
> }
>
> Or would I need to foreach over the enum somehow?

find + EnumMembers should do the trick
if ( (EnumMembers!SomeType).canFind(value))
{
     // ...
}



More information about the Digitalmars-d-learn mailing list