Convert String to Enum

From Birnam Designs Wiki

Jump to: navigation, search

example for converting a string to an enum:

  1. enum Colour { Red, Green, Blue };
  2. Colour c = (Colour)Enum.Parse(typeof(Colour), "Red", true);
  3. Console.WriteLine("Colour Value: {0}", c.ToString());
  4.  
  5. // Picking an invalid colour throws an ArgumentException. To
  6. // avoid this, call Enum.IsDefined() first, as follows:
  7. string nonColour = "Polkadot";
  8. if (Enum.IsDefined(typeof(Colour), nonColour)) 
  9.      c = (Colour)Enum.Parse(typeof(Colour), nonColour, true);
  10. else
  11.      MessageBox.Show("Uh oh!");

thanks!

Share This!
This page was last modified on 11 February 2010, at 19:38. This page has been accessed 598 times.