Convert Enum To String In C#

Updated: 3/7/2017 

This was an old article. Now, we can convert an enum to string by calling the ToString() method.
  1. class Program  
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.         Enum wkday = Weekday.Friday;  
  6.         Console.WriteLine("Enum string is '{0}'", wkday.ToString());  
  7.         Console.ReadKey();  
  8.     }  
  9.           
  10.     // Enum   
  11.     public enum Weekday  
  12.     {  
  13.         Monday = 0, Tuesday = 1, Wednesday = 2, Thursday = 4, Friday = 5, Saturday = 6, Sunday = 7  
  14.     }  
  15. }   
Original post 
 
I have an enum SortFilter, which looks like following: 

  1. public enum SortFilter  
  2. {  
  3.       FirstName = 0,  
  4.       LastName = 1,  
  5.       Age = 2,  
  6.       Experience = 3
  7. }   

Now, let's say I want to display the string value of enum in some control. For that, I will have to convert Enum value to a string. The following code loops through enum and adds string values to a DropDownList. 

  1. SortByList.Items.Clear();  
  2. // Conversion from Enum to String  
  3. foreach (string item in Enum.GetNames(typeof(ArrayListBinding.SortFilter)))  
  4. {  
  5.       SortByList.Items.Add(item);  
  6. }     

This code converts an enum to string: 

  1. string name= Enum.GetName(typeof(ArrayListBinding.SortFilter), SortFilter.FirstName);   

Now let's say, you have an enum string value say, "FirstName" and now you want to convert it to 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), "FirstName");   

Up Next
    Ebook Download
    View all
    Learn
    View all