Enumerator to String to Enumerator

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

It's possible to convert an enumerator to a string with the ToString method,
but is it possible to convert the string back to an enumerator?

For example:

enum Enumeration
{
enum1,
enum2,
}

void Test ()
{
Enumeration e = Enumeration.enum1;

// Get the enumerator name
string s = e.ToString (); // s = 'enum1'

// Convert enumerator name back to an enumerator
Enumeration e2 = (Enumeration) s; // e2 = Enumeration.enum1;
}

Obviously the above code won't work, but it should demonstrate what I'm
trying to do. Is there way to do this? If not, what do you think would be the
best way to work around this?

Thanks
 
Barguast said:
It's possible to convert an enumerator to a string with the ToString method,
but is it possible to convert the string back to an enumerator?

Use Enum.Parse.
 
Look at the Parse method

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

It's possible to convert an enumerator to a string with the ToString method,
but is it possible to convert the string back to an enumerator?

For example:

enum Enumeration
{
enum1,
enum2,
}

void Test ()
{
Enumeration e = Enumeration.enum1;

// Get the enumerator name
string s = e.ToString (); // s = 'enum1'

// Convert enumerator name back to an enumerator
Enumeration e2 = (Enumeration) s; // e2 = Enumeration.enum1;
}
 

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

Back
Top