Click here to Skip to main content
15,883,776 members
Articles / Programming Languages / C#

String enumerations in C#

Rate me:
Please Sign up or sign in to vote.
1.95/5 (7 votes)
26 Jul 2007CPOL 14.6K   8  
String enumerations for two way binding.

Introduction

I found this article a few months back on CodeProject: stringenum.aspx. It is an impressive, nice way to get enums to carry string values using attributes. After using it, I found myself with a strange need to go the other way round; i.e., given the string value, get the enum value that string is associated with.

Background

I suggest reading the article from the link above first. That article will get you to 90% of the path to "getting strings associated with enums". I am extending the functionality here to go the other way round.

Using the code

C#
//
// Code from http://www.codeproject.com/csharp/stringenum.asp
//
 public class StringEnum
 {
     private Type _enumType;

     /// <summary>
     /// Creates a new <see cref="StringEnum"/> instance.
     /// </summary>
     /// <param name="enumType">Enum type.</param>
     public StringEnum(Type enumType)
     {
         if (!enumType.IsEnum)
            throw new ArgumentException(String.Format(
                      "Supplied type must be an Enum. Type was {0}",
                      enumType.ToString()));

         _enumType = enumType;
    }

    /// <summary>
    /// Gets a string value for a particular enum value.
    /// Developer(s): http://www.codeproject.com/csharp/stringenum.asp,
    /// modified by Kiran Bheemarti
    /// </summary>
    /// <param name="value">Value.</param>
    /// <returns>String Value associated via a
    /// <see cref="StringValueAttribute"/> attribute,
    /// or null if not found.</returns>
    public static string GetStringValue(Enum value)
    {
        Type type = value.GetType();

        //Look for our 'StringValueAttribute' in the field's custom attributes
        FieldInfo fi = type.GetField(value.ToString());
        StringValueAttribute[] attrs = fi.GetCustomAttributes(
          typeof(StringValueAttribute), false) as StringValueAttribute[];

        return (attrs.Length > 0) ? attrs[0].Value : null;
    } 
}

public class StringValueAttribute : Attribute
{
    private string _value;

    /// <summary>
    /// Creates a new <see cref="StringValueAttribute"/> instance.
    /// </summary>
    /// <param name="value">Value.</param>
    public StringValueAttribute(string value)
    {
        _value = value;
    }

    /// <summary>
    /// Gets the value.
    /// </summary>
    /// <value></value>
    public string Value
    {
        get { return _value; }
    }
}

Additional functionality to get enum given string

C#
/// <summary>
/// Gets the Enum given the associated string and the index of the string
/// Developer(s): Kiran Bheemarti
/// </summary>
/// <typeparam name="T"></typeparam>
<param name="value"></param>
/// <returns></returns>
public static T GetEnumForGivenString<T>(string value, int NthOccurence) 
{
    if (!typeof(T).IsEnum)
        throw new ArgumentException(String.Format(
           "Supplied type must be an Enum. Type was {0}",
           typeof(T).ToString()));

    T result = default(T);
    int foundAtIndex = 0;

    foreach (string str in Enum.GetNames(typeof(T)))
    {
        if (GetStringValue((Enum) Enum.Parse(typeof(T), str, true)) == value)
        {
            foundAtIndex++;
            if(foundAtIndex == NthOccurence)
            {
                result = (T)Enum.Parse(typeof(T), str, true);
                break;
            }
        }
    }

    return result;
}

Download the code from the referenced article and add the method given above.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --