Reusing pieces of code is liked picking off sentences from other people's stories and trying to make a magazine article. --Bob Frankston
Welcome to my blog and project site for Microsoft.NET development.

I've been a full time .NET developer for ten years, but I didn't start my professional life as a programmer ... more
Share/Print this page:
Old Cars - 11/2011. Copyright © Steve Lautenschlager.

Convert String to Enum Instance

By steve on January 09, 2007.
Updated on January 15, 2012.
Viewed 183,073 times (232 times today).
Article TypesLanguage ElementsLanguage ElementsLanguage ElementsLanguagesTechnologies
SnippetConversionsEnumsText and StringsC#.NET

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

User Comments (8)

Posted 2008 May 01 13:24 PM. reply
What if the string does not have an valid representation in the specific enum?
i.e.:

public void illegalDayOfWeek()
{
DayOfWeek illegal = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), "illegal");
}

David H.
Replied 2008 May 01 13:27 PM by David H.. reply
What if the string does not have an valid representation in the specific enum?
i.e.:

public void illegalDayOfWeek()
{
DayOfWeek illegal = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), "illegal");
}

<a href="http://msdn.microsoft.com/en-us/library/kxydatf9.aspx#ddueExceptionsToggle">Found the answer myself</a>. And ashamingly easy too.
It will trow an ArgumentException
Posted 2009 May 19 18:44 PM. reply
thank you. i was looking exactly for this.

Bulent
Posted 2010 Oct 27 05:54 AM. reply
Or for a more generic helper method ....


/// <summary>
/// Converts a sting into an element of the specified enum
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="enumString"></param>
/// <returns></returns>
public static T ConvertStringToEnum<T>(string enumString)
{
try
{
return (T)Enum.Parse(typeof(T), enumString, true);
}
catch (Exception ex)
{
// Create an instance of T ... we're doing this to that we can peform a GetType() on it to retrieve the name
//
T temp = default(T) ;
String s = String.Format("'{0}' is not a valid enumeration of '{1}'", enumString, temp.GetType().Name);
throw new Exception(s, ex);
}
}

Alan
Replied 2011 Nov 08 16:22 PM by Keith Ball. reply
Instead of using "T temp = default(T)" you can use typeof(T).Name Creating a default instance of T can be very dangerious depending on what the objects parameterless constructor does.
Posted 2010 Nov 17 03:47 AM. reply
that was really helpful, thanks. keep posting

suman modi
Posted 2011 Apr 27 07:38 AM. reply
Full explanation..
http://www.docstorus.com/viewer.aspx?code=833d27e2-5e3b-4ec0-b950-02c8fc2ec572&title=How%20to%20use%20Enum%20with%20Combobox%20in%20C#%20WinForms%20and%20Asp.Net

e?
Posted 2012 Jan 09 05:00 AM. reply
This is one of the best answer so far, I have read online. Just useful information. Very well presented. Thanks for sharing with us. I had found another nice post with wonderful explanation on Enumeration in c#, which is also helped me to complete my task. For more details of that post check out this link.... http://mindstick.com/Articles/ade257fc-7058-4f60-a0fe-85c7ca52f004/?Enumeration%20in%20c# Thanks everyone for your precious post.

Bhupendar Singh
Post Your Comment
  You may post without logging in or login here.
Display Name: Required.
Email: Required. Will not be shown. Used for identicon.
Comment:
Allowed tags: <quote></quote>, <code></code>, <b></b>, <i></i>, <u></u>, <red></red>
 
   Please type text as shown in the image at left.