C# Enum To String Using Attributes


There are certain situation we need to have custom string value to a Enum and later need to retrieve the string value. The string value should be independent of the enum constant. The below example will use the system.attribute class to achieve this.

Step 1: Declare a Enum

public enum GameConsole
{
    PSP=0,
    PS2=1,
    XBOX=2,
    Nitendo=3
}

Step 2: Create a custom Attribute called EnumValue

public class EnumValue : System.Attribute
{
    private string _value;
    public EnumValue(string value)
    {
         _value = value;
    }
    public string Value
    {
        get { return _value; }
    }
}

Step 3: Create a example to retrieve a attribute value

public static class EnumString
{
    public static string GetStringValue(Enum value)
    {
    string output = null;
    Type type = value.GetType();
    FieldInfo fi = type.GetField(value.ToString());
    EnumValue[] attrs = fi.GetCustomAttributes(typeof(EnumValue),false) as EnumValue[];
    if (attrs.Length > 0)
    {
        output = attrs[0].Value;
    }
        return output;
    }
}

Step 4: Change the Enum to add the string with attribute

public enum GameConsole
{
    [EnumValue(“Play Station Portable”)]
    PSP=0,
    [EnumValue(“Play Station 2”)]
    PS2=1,
    [EnumValue(“Microsoft Gaming Console”)]
    XBOX=2,
    [EnumValue(“WII Nitendo”)]
    Nitendo=3
}

Step 5: Get the Enum Attribute value

String enumStringValue = EnumString.GetStringValue(GameConsole.PSP);

1 thought on “C# Enum To String Using Attributes

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s