Convert string to enum

Sometimes we may need to read a Config value using ConfigurationSettings.AppSettings and assign it to a Enum. This function helps to convert a string to Enum.

/// <summary>
/// Function to retrive Enum value by giving the corresponding string value.(This method is case sensitive)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value">The value.</param>
/// <returns>Enum value</returns>
public static T ToEnum<T>(string value)
{
    //This method will throw error if the case of the value is different from the
    //enum value.
    if (Enum.IsDefined(typeof(T), value))
    {
        return (T)Enum.Parse(typeof(T), value, true);
    }
    throw new ArgumentException("Value doesn't exists in the Enum");
}
This entry was posted in .Net, .Net 3.0 / 3.5, ASP.Net and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>