Giving C# enums string values using attributes and extension methods

Every now and then I stumble across code where it could be useful to have a string value associated with an enum value, but it seems not well known how to do this, hence this blogpost.

First we need some usings:

using System;
using System.Linq;
using System.Reflection;

Now let’s see how our Enum will look like, we can add a string value as attribute to each enum value:

public enum Color
{
    [EnumStringValue("R")]
    Red,
    [EnumStringValue("G")]
    Green,
    [EnumStringValue("B")]
    Blue
}

To get this to work, first we need a class for our attribute:

[AttributeUsage(AttributeTargets.Field)]
public class EnumStringValueAttribute : Attribute
{
    public EnumStringValueAttribute(string value)
    {
        StringValue = value;
    }
    public string StringValue { get; set; }
}

With this we can already compile our code, but we need something more to actually access the values:

public static class EnumExtensions
{
    public static string GetStringValue(this Enum enumValue)
    {
        Type type = enumValue.GetType();
        FieldInfo fieldInfo = type
            .GetField(enumValue.ToString());
        return fieldInfo
            .GetCustomAttributes<EnumStringValueAttribute>(false)
            .FirstOrDefault()?.StringValue;
    }
}

Now it’s ready to use. As it’s an extension method, you can access it directly though any enum value:

Color.Red.GetStringValue();

Leave a Reply

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