How to convert a string to an enum in C#

C# enum or enumeration is a value data type. This code example shows how to convert an enum to a string in C#. Code also shows how to convert a string to an enum in C#.
 
Let's say, I have an enum named SortFilter, which looks like the following. As you can see here, the enum has four values. 
  1. public enum SortFilter  
  2. {  
  3. Top,  
  4. Bottom,  
  5. Left,  
  6. Right
  7. }  
An enum in C# is declared using the enum keyword followed by its name and curly braces. If you're new to enums, learn here, Enums in C#.
 
Now, let's say I want to display the string values of an enum in a control such as a dropdown. For that, I will have to convert Enum values to string values. For example, I want to add all enum string values to a DropDownList.
 
The following code loops through an enum and adds string values to the control. Here SortByList is a DropDownList control.
  1. SortByList.Items.Clear();  
  2. // Conversion from Enum to String  
  3. foreach (string item in Enum.GetNames(typeof(SortFilter)))  
  4. {  
  5. SortByList.Items.Add(item);  
  6. }  
In the above code, I've used Enum.GetNames(EnumName) method that returns all enum values. I've used a foreach loop to iterate through the enum values and add them to a DropDownList control. 
 
We can use Enum.GetName static method to convert an enum value to a string. The following code uses Enum.GetName static method that takes two arguments, the enum type and the enum value. Here, I've used typeof operator to get the type of the enum and passed one enum value that I want to convert to string.
  1. string name= Enum.GetName(typeof(SortFilter), SortFilter.Top);
Now let's say, you have an enum string value say, "Bottom" and now you want to convert it to back to the Enum value. The following code converts from a string to enum value, where Developer.SortingBy is of type SortFilter enumeration:
  1. // Conversion from String to Enum  
  2. Developer.SortingBy = (SortFilter)Enum.Parse(typeof(SortFilter), "Bottom");
Still not sure? Want more? Here is a clear explaination of enum questions, Most Common 7 C# Enum Examples.
 


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.