www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How to parse enum from a string ?

reply Vinod K Chandran <kcvinu82 gmail.com> writes:
Hi all,
Assume that i have an enum like this.
enum TestEnum  {
     Received = 1,
     Started ,
     Finished ,
     Sent
}

I am saving this enum values as string in database. So, when i 
retrieve them from the database, how can i parse the string into 
TestEnum ? In vb. net, i can use
[Enum].Parse(GetType( TestEnum), "Started")
How to do this in D ?
May 27 2020
next sibling parent WebFreak001 <d.forum webfreak.org> writes:
On Wednesday, 27 May 2020 at 17:33:33 UTC, Vinod K Chandran wrote:
 Hi all,
 Assume that i have an enum like this.
 enum TestEnum  {
     Received = 1,
     Started ,
     Finished ,
     Sent
 }

 I am saving this enum values as string in database. So, when i 
 retrieve them from the database, how can i parse the string 
 into TestEnum ? In vb. net, i can use
 [Enum].Parse(GetType( TestEnum), "Started")
 How to do this in D ?
you can convert an enum to a string using myEnum.to!string and you can similarly convert strings back to the enum using someString.to!TestEnum (import std.conv for both of them) Example: https://run.dlang.io/is/UeLjJS
May 27 2020
prev sibling parent reply Dennis <dkorpel gmail.com> writes:
On Wednesday, 27 May 2020 at 17:33:33 UTC, Vinod K Chandran wrote:
 I am saving this enum values as string in database. So, when i 
 retrieve them from the database, how can i parse the string 
 into TestEnum ?
Use `to` from `std.conv`. ``` import std.conv: to; void main() { assert("Received".to!TestEnum == TestEnum.Received); } ```
May 27 2020
parent Vinod K Chandran <kcvinu82 gmail.com> writes:
On Wednesday, 27 May 2020 at 17:36:35 UTC, Dennis wrote:
 On Wednesday, 27 May 2020 at 17:33:33 UTC, Vinod K Chandran 
 wrote:
 I am saving this enum values as string in database. So, when i 
 retrieve them from the database, how can i parse the string 
 into TestEnum ?
Use `to` from `std.conv`. ``` import std.conv: to; void main() { assert("Received".to!TestEnum == TestEnum.Received); } ```
Hi, Thanks a lot. It worked. :)
May 27 2020