Thursday, December 8, 2011

convert a string into an enum

object Enum.Parse(System.Type enumType, string value, bool ignoreCase)

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


ref: http://blogs.msdn.com/b/tims/archive/2004/04/02/106310.aspx

No comments:

Post a Comment