Convert String to enum in C#

In this article we will discuss about how to convert a string to an enum value.
  • 4826

Here we will convert from string to enum. For this Enum.Parse() method is used. Enum keyword is used to declare enumeration, a distinct type consisting of a set of named constant called enumeration. It is declare like this.

enum Colors {Red, Green, Yellow, Orange};

In this enumeration Red is 0,Geen is 1,Yellow is 2 and so on. The enumerators can have initializers to override the default value.

For example:
enum colors {Red=2,Green,Yellow,Orange};
In this enumeration the sequence of elements is forced to start from 2 instead of 0.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication5
{
    class Program
    {
        enum Colors { None = 0, Red = 1, Green = 2, Blue = 4 };
        static void Main(string[] args)
        {
            string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" };
            foreach (string colorString in colorStrings)
            {
                try
                {
                    Colors colorValue = (Colors)Enum.Parse(typeof(Colors), colorString);
                    if (Enum.IsDefined(typeof(Colors), colorValue) | colorValue.ToString().Contains(","))
                        Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString());
                    else
                        Console.WriteLine("{0} is not an underlying value of the Colors enumeration.", colorString);
                }
                catch (ArgumentException)
                {
                    Console.WriteLine("'{0}' is not a member of the Colors enumeration.", colorString);
                }
            }
            Console.ReadLine();
        }
    }
}


Further Readings
  
You may also want to read these related articles.

Ask Your Question 

Got a programming related question? You may want to post your question here
 

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.