How do you convert a string into an enum?
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...
Comments
Anonymous
April 02, 2004
Do you have something similar to this in VB?Anonymous
April 02, 2004
Venu, the old proverb says that it's better to teach a man to fish than to simply give him a fish, so I'm going to point you at an automated conversion tool from C# to VB:
http://www.kamalpatel.net/ConvertCSharp2VB.aspx
Simply copy and paste the code above into the tool, and you'll get the C# equivalent. Cool, isn't it?Anonymous
April 02, 2004
You can get the string values of enums also by calling Enum.GetNames or Enum.GetName...Anonymous
April 06, 2004
The problem occurs when the Enum definition is made of multiple words.
Another more flexible approach (albeit much slower) is to adhorn each Enum value with a DescriptionAttribute, and to use reflection to grab thatAnonymous
April 19, 2005
Excellent! Like you said, glaringly obvious.Anonymous
July 14, 2005
Great! That was exactly what I was looking for!Anonymous
October 31, 2005
How about the C version of this...
that would be really helpful...Anonymous
December 28, 2005
Very helpful - Thanks!
Can I get this in COBOL, 8088 assembly, and Pascal too? No hurry, I need it by next Wednesday.
Thanks again!Anonymous
February 25, 2006
Hi, i was just wondering if you knew how I could do this exact thing in C++.NET? I have found so many C# examples but they all seem so different to what I am used to.
Many thanks,
JohnAnonymous
April 11, 2006
Well here's a small example using managed C++:
namespace EnumMagic
{
public __gc class MagicSet
{
public:
__value enum MagicItems
{
WAND
, POINTY_HAT
, RABBIT
, SCARF
, PLAYING_CARDS
, PIDGEON
};
};
}
int _tmain()
{
String* aNewEnumString = __box( EnumMagic::MagicSet::PLAYING_CARDS )->ToString();
EnumMagic::MagicSet* aNewMagicSet = new EnumMagic::MagicSet();
if ( Enum::IsDefined( __typeof( EnumMagic::MagicSet::MagicItems ), S"RABBIT" ) )
{
aNewMagicSet =
static_cast< EnumMagic::MagicSet* >( Enum::Parse( __typeof( EnumMagic::MagicSet::MagicItems ), S"RABBIT" ) );
}
if ( Enum::IsDefined( __typeof( EnumMagic::MagicSet::MagicItems ), S"PRETTY_ASSISTANT" ) )
{
aNewMagicSet =
static_cast< EnumMagic::MagicSet* >( Enum::Parse( __typeof( EnumMagic::MagicSet::MagicItems ), S"PRETTY_ASSISTANT" ) );
}
return 0;
}Anonymous
April 18, 2006
genius. cheers. was just about to break out the giant switch.Anonymous
May 02, 2006
The C# to VB.NET is great, but what about just plain VB or VBA?Anonymous
May 04, 2006
The comment has been removedAnonymous
July 26, 2006
Thank you,
it is a shame that enum_type written does not inherit capabilities of base enum.Anonymous
August 16, 2006
Thanks !Anonymous
September 22, 2006
Thanks, was struggling with this for about 3 minutes then found your doc.Anonymous
November 07, 2006
Thanks for the suggession and for providing same code.Anonymous
November 08, 2006
The comment has been removedAnonymous
January 06, 2007
Holas! Ya en un post del anio pasado xD, habíamos comentado como usar una estructura enumeración...Anonymous
January 06, 2007
Holas! Ya en un post del anio pasado xD, habíamos comentado como usar una estructura enumeración en elAnonymous
November 20, 2007
PingBack from http://sdesmedt.wordpress.com/2007/11/20/offline-maps-added-ripping-functionality-and-released-it-as-version-1001/Anonymous
April 23, 2008
How do you convert a string into an enumeration? object Enum .Parse(System. Type enumType, string valueAnonymous
April 24, 2008
You've been kicked (a good thing) - Trackback from DotNetKicks.comAnonymous
May 06, 2008
PingBack from http://www.marcosdellantonio.net/2008/05/07/como-converter-uma-string-para-um-elemento-de-uma-enumeracao/Anonymous
May 09, 2008
Convert enum to string with attributes.Anonymous
May 09, 2008
Convert enum to string with attributes.Anonymous
May 28, 2008
PingBack from http://rtipton.wordpress.com/2008/05/04/weekly-link-post-40/Anonymous
June 13, 2008
PingBack from http://www.hanselman.com/blog/BackToBasicsLifeAfterIfForAndSwitchLikeADataStructuresReminder.aspxAnonymous
June 13, 2008
I just had a great one on one coding learning session with a good friend of mine over lunch. He's tryingAnonymous
August 05, 2008
PingBack from http://www.gigpeppers.com/blog/?p=3Anonymous
August 06, 2008
PingBack from http://ciappara.wordpress.com/2008/08/06/convert-a-string-to-enum/Anonymous
October 08, 2008
Dnes len tak pri bežnom dennom kódení vyvstala z môjho kódu interná potreba textového enumeration typuAnonymous
March 05, 2009
PingBack from http://xvsb.wordpress.com/2009/03/05/15/