Updated: 3/7/2017
This was an old article. Now, we can convert an enum to string by calling the ToString() method.
- class Program
- {
- static void Main(string[] args)
- {
- Enum wkday = Weekday.Friday;
- Console.WriteLine("Enum string is '{0}'", wkday.ToString());
- Console.ReadKey();
- }
-
-
- 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 following:
- public enum SortFilter
- {
- FirstName = 0,
- LastName = 1,
- Age = 2,
- Experience = 3
- }
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.
- SortByList.Items.Clear();
-
- foreach (string item in Enum.GetNames(typeof(ArrayListBinding.SortFilter)))
- {
- SortByList.Items.Add(item);
- }
This code converts an enum to string:
- 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:
-
- Developer.SortingBy = (SortFilter)Enum.Parse(typeof(SortFilter), "FirstName");