C# Parsing string representation of an enum field


Many time we need to parse enum fields string values to type. For this I have written one generic utility method which will do this safely.

Utility method to parse enum string

public static T ParseEnum<T>(string value, T defaultValue) where T : struct, IConvertible
{
    if (!typeof(T).IsEnum)
        throw new ArgumentException("T must be an enumerated type");

    if (string.IsNullOrEmpty(value))
        return defaultValue;

    foreach (T item in Enum.GetValues(typeof(T)))
    {
        if (item.ToString().Equals(value, StringComparison.OrdinalIgnoreCase))
            return item;
    }
    return defaultValue;
}

Example to using this method for Rights enum.

Rights right = Utils.ParseEnum<Rights>(r.Trim(), Rights.None);

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.