How do you convert a string into an enum?

  • Post author:
  • Post category:
  • Post comments:0 Comments
  • Post last modified:March 22, 2005

출처: http://blogs.msdn.com/tims/archive/2004/04/02/106310.aspx

I’ve come across the situation on a number of occasions when coding where I’ve wanted to convert from a string to an enum. In the Media Catalog sample, I resorted to one giant switch statement that has a case block for each string that returns an enum from it.

One of my colleagues came up with the answer yesterday; 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, Simon!

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; no doubt someone like Brad could cast light on it…

Author Details
Kubernetes, DevSecOps, AWS, 클라우드 보안, 클라우드 비용관리, SaaS 의 활용과 내재화 등 소프트웨어 개발 전반에 도움이 필요하다면 도움을 요청하세요. 지인이라면 가볍게 도와드리겠습니다. 전문적인 도움이 필요하다면 저의 현업에 방해가 되지 않는 선에서 협의가능합니다.
0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments