German Wear Discount Shop - Click Here Write for Dotnet-friends and earn for your each submission [Dot]Net-Friends
Skip Navigation Links
Home
Latest
Fast Code
Articles
Tutorials
Online Resources
Forums
Login   | Hi, Guest


How do you convert a string into an enum?
Written By Omer Kamal On 06/05/2008

Later I was implementing a web service, where I was supposed to use a given enum as a parameter dynamically. I was converting my selected string type to the given enum type. This below code will help you with this kind of operation.

Views: 373
Rating: 4
Login to Rate
omerkamal
Tagged Under: General, Language Specifications, Web Services

Explanation:

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

Footnote: interestingly, whilst writing this up I noticed that Enum.IsDefined() doesn’t offer the ignoreCase parameter. If you don’t know whether the casing is right, it seems the only way to do the conversion is using the Parse method and catching the ArgumentException. That's not ideal, since it runs a lot slower. I wonder if this is a loophole in the design.

Delicious Digg reddit reddit Technorati
About the Author:

@@ Omer Kamal is a Software Developer at Elanize KG Germany. He MSc. Mathematics from Islamia University Bahawalpur, Pakistan and Certified Developer from National Institute of Electronics Islamabad, Pakistan. He is Founder of FriendsPoint.de and Dotnet-Friends.com. He is currently Involved with Microsoft Office SharePoint 2007, Microsoft Dynamics CRM, BI Portal Solutions (Microsoft Dynamics Customization) and Web Security Solutions.
Check Omer Kamal Profile

Related Useful Links:
Visitors/Readers Comments
(for questions please use The Forum)



"Be the First to Comment!"


Add your Comments

Name:  
Message:
Note: For faster response please use Forums >> for your questions instead of the comments area! (Admin)