Enum question

  • Thread starter ChInKPoInt [No MCSD]
  • Start date
C

ChInKPoInt [No MCSD]

Say, if I got this enum defined:

enum Colors { Red = 1, Green = 2, Blue = 4 }

If someone passes me a string with value "Red" , how can I Cast it to enum
or convert the variable so that it returns Colors.Red?

string mystring = "Red";
 
G

Guest

Hi,

You can use the Parse method of the Enum class. Try this:

string mystring = "Red";
Colors myEnum = (Colors)Enum.Parse(typeof(Colors),mystring);
Console.WriteLine("My Color is : {0}", myEnum.ToString());


Hope this helps.
 

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

Top