Convert an Enum to a String in C#

C# Enum To String

We can convert an enum to a string by calling the ToString() method of an Enum. The following code example shows how to convert an enum to a string in C#.

class Program  
{  
    static void Main(string[] args)  
    {  
        Enum wkday = Weekday.Friday;  
        Console.WriteLine("Enum string is '{0}'", wkday.ToString());  
        Console.ReadKey();  
    }  
          
    // Enum   
    public enum Weekday  
    {  
        Monday = 0, Tuesday = 1, Wednesday = 2,
 Thursday = 4, Friday = 5, Saturday = 6, Sunday = 7  
    }  
}

Original post 

I have an enum SortFilter, which looks like the following:

public enum SortFilter  
{  
      FirstName = 0,  
      LastName = 1,  
      Age = 2,  
      Experience = 3
}

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

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

The following code converts an enum to a string:

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

Now let's say you have an enum string value, "FirstName", and you want to convert it to an Enum value. The following code converts from a string to an enum value, where Developer.SortingBy is of type SortFilter enumeration:

// Conversion from String to Enum  
Developer.SortingBy = (SortFilter)Enum.Parse(typeof(SortFilter), "FirstName");

Summary

This post with code example taught us how to convert an enum into a string in C#.


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.