The best is the enemy of the good. --Voltaire

Convert String to Enum Instance

By steve on Tuesday, January 9, 2007.
Updated Saturday, January 12, 2013.
Viewed 260,112 times. (11 times today.)
DeveloperTips and TutorialsC#
Old Cars - 11/2011. Copyright © Steve Lautenschlager.

Summary

Enums are a powerful construction in C# and other programming languages when you are working with finite sets such as fruits, days of the week or colors. Visual Studio's Intellisense is very nice with Enums because it lists all the options for the programmer to choose from.

But quite often you want to print enums, compare int values, or serialize an enum--and then you have to do some conversions.

The following method may be run in the code-behind file of an ASPX page where you have added a Label control named lblOutput. However, this technique will work in any C# program, not just ASP.NET.

Example: Convert string to Enum instance

public void EnumInstanceFromString()
{
   // The .NET Framework contains an Enum called DayOfWeek.
   // Let's generate some Enum instances from strings.

   DayOfWeek wednesday = 
      (DayOfWeek)Enum.Parse(typeof(DayOfWeek), "Wednesday");
   DayOfWeek sunday = 
      (DayOfWeek)Enum.Parse(typeof(DayOfWeek), "sunday", true);
   DayOfWeek tgif = 
      (DayOfWeek)Enum.Parse(typeof(DayOfWeek), "FRIDAY", true);

   lblOutput.Text = wednesday.ToString() 
      + ".  Int value = " + ((int)wednesday).ToString() + "<br>";
   lblOutput.Text += sunday.ToString() 
      + ".  Int value = " + ((int)sunday).ToString() + "<br>";
   lblOutput.Text += tgif.ToString() 
      + ".  Int value = " + ((int)tgif).ToString() + "<br>";

}

The Enum.Parse method takes two or three arguments. The first is the type of the enum you want to create as output. The second field is the string you want to parse. Without a third input, the case of the input string must match an enum instance or the conversion fails. But the third input indicates whether to ignore case. If true, than wEdNEsDAy will still get converted successfully.

Example: Output

Wednesday. Int value = 3
Sunday. Int value = 0
Friday. Int value = 5
Back to Top

Share This Page:


Subscribe for free and read it when and where you want!

Get the latest tips and tools in your Inbox.

Your email address will NEVER be shared and you can unsubscribed at any time using the link at the bottom of every email.

Click Here to Subscribe

(Was this post helpful? If not, please leave a comment and let me know what you would like to hear about.)


 
comments powered by Disqus
Follow:
Share This Page:


Get the latest tips and tools in your Inbox. It's 100% free.



Click Here to Subscribe
Welcome!
Welcome to my blog about software development and the Microsoft stack.

I've been a full time .NET developer for fifteen years, but I didn't start my professional life as a programmer ... more