How do I Convert a String to an Enum Value?

Introduction

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

public enum SortFilter
{
FirstName,
LastName,
Age,
Experience
}

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. For example, I want to add all enum string values to a DropDownList. Here SortByList is DropDownList. The following code loops through the enumeration and adds string values to it.

SortByList.Items.Clear();

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

} 

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

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

Note. Quach adds the below note. See below article comments for more details.

You can also access the enum using GetValues and GetName:

using System;
namespace Test
{
  public class Class1
  {
    enum Fruit
    {
      Orange,
      Apple,
      Cherry,
      Banana
    }

    public static void Main(string[] args)
    {
      foreach (Fruit f in Enum.GetValues(typeof(Fruit)))
      {
        Console.WriteLine(f);
      }
      string name = Enum.GetName(typeof(Fruit), Fruit.Cherry);
      Console.WriteLine(name);
    }
  }
}

Summary

This article taught us how to convert a String to an Enum Value. 

If you require any clarification/suggestions on the article, please leave your questions and thoughts in the comment section below. Follow C# Corner to learn more new and amazing things about Programming or to explore more technologies.

Thanks for reading, and I hope you like it.


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.