SIGN UP MEMBER LOGIN:    
ARTICLE

How do I Convert a String to an Enum Value?

Posted by Mahesh Chand Articles | How do I September 10, 2005
In this How do I, you will learn how to convert a string to an enum value in C#.
Reader Level:
Download Files:
 

I have an enum SortFilter, which looks like following:

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

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

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 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:

// Conversion from String to Enum

Developer.SortingBy = (SortFilter)Enum.Parse(typeof(SortFilter), "FirstName");  

Note: The below note is added by Quach. See below article comments for more details.

You can also access 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);
}
}
}

Login to add your contents and source code to this article
share this article :
post comment
 

You can also access 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);
     
    }
  }
}

Posted by Quach Nov 18, 2005
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor