Click here to Skip to main content
Click here to Skip to main content

String enumerations in C#

, 26 Jul 2007 CPOL
Rate this:
Please Sign up or sign in to vote.
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

//
// 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

/// <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)

Share

About the Author

Kiran Bheemarti
Web Developer
United States United States
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150224.1 | Last Updated 27 Jul 2007
Article Copyright 2007 by Kiran Bheemarti
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid