Associating Enums with strings in C#

How many times have you needed to associate a specific Enum with a different string? How have you solved this? Let’s see an example:

public enum Status
{
    New,
    Pending,
    FileNotFound,
    Processed
}

if we use the ToString() method, it will display “FileNotFound” instead of a nicer “File Not Found”.

One solution could be using reflection! We can just add a Description attribute to those enums that we want to have a different text:

public enum Status
{
    New,
    Pending,
    [Description("File Not Found")]
    FileNotFound,
    Processed
}

And then we would need to add a new method to get the new attribute (I would also recommend to use the extension method for this, read my post Extension Methods in C# for more information)

public static string GetEnumDescription(this Enum value)
{
   var fi = value.GetType().GetField(value.ToString());
   var attributes =
(DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

   if (attributes != null && attributes.Length > 0)
      return attributes[0].Description;

   //if no attribute was specified, then we will return the regular enum.ToString()
   return value.ToString();
}

You would only need to add this method somewhere on your project and that’s it! we could use the description attribute and the method Status.FileNotFound.GetEnumDescription() to get the description, and if there is not description specified, then it will return the string of the enum. Also, we could use the same idea if we support multi-language (indicating the key here instead).

Please follow: