High-Performance Development - C#, VB, SQL, ASP.NET

Slogan Text

This article describes how to convert a string representation of an enum into the corresponding enum value using ASP.NET, C#.

We use the Enum.Parse method to perform the conversion. The Enum.Parse method accepts the enum type, the string name of the enum value, and a boolean indicating whether to ignore the case of the string name.

We use the try\catch block to catch any conditions when the ColorName does not match any of the enum values.

Example

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace SandyPondResources
{
    public class SPR_HowToConvertStringToEnum
    {
        public enum Colors
        {
            Blue,
            Green,
            Red
        }

        public bool ConvertToEnum(string ColorName, ref Colors Color)
        {
        try
        {
            Color = (Colors)Enum.Parse(typeof(Colors), ColorName, true);
        }
        catch
        {
            return false;
        }

        return true;
        }
    }
}