How do you convert a string into an enum? - Online Free Computer Tutorials.

'Software Development, Games Development, Mobile Development, iOS Development, Android Development, Window Phone Development. Dot Net, Window Services,WCF Services, Web Services, MVC, MySQL, SQL Server and Oracle Tutorials, Articles and their Resources

Tuesday, May 31, 2011

How do you convert a string into an enum?

How do you convert a string into an enum?

 it's one of those methods that you can never find when you're looking for it, but once discovered it seems blindingly obvious:

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

So you can write the following kind of code:

   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!");

What a time saver - thanks

No comments:

Post a Comment