Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum ToString with user friendly strings

Tags:

c#

enums

tostring

My enum consists of the following values:

private enum PublishStatusses{     NotCompleted,     Completed,     Error }; 

I want to be able to output these values in a user friendly way though.
I don't need to be able to go from string to value again.

like image 748
Boris Callens Avatar asked Jan 26 '09 10:01

Boris Callens


People also ask

Can we convert enum to string?

We can convert an enum to string by calling the ToString() method of an Enum.

What is enum toString?

The Java Enum has two methods that retrieve that value of an enum constant, name() and . toString(). The toString() method calls the name() method which returns the string representation of the enum constant. In listing 1, the value returned by calling the name() and toString() on an Animal.

Can enums contain strings?

No they cannot. They are limited to numeric values of the underlying enum type.


1 Answers

I use the Description attribute from the System.ComponentModel namespace. Simply decorate the enum:

private enum PublishStatusValue {     [Description("Not Completed")]     NotCompleted,     Completed,     Error }; 

Then use this code to retrieve it:

public static string GetDescription<T>(this T enumerationValue)     where T : struct {     Type type = enumerationValue.GetType();     if (!type.IsEnum)     {         throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");     }      //Tries to find a DescriptionAttribute for a potential friendly name     //for the enum     MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());     if (memberInfo != null && memberInfo.Length > 0)     {         object[] attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);          if (attrs != null && attrs.Length > 0)         {             //Pull out the description value             return ((DescriptionAttribute)attrs[0]).Description;         }     }     //If we have no description attribute, just return the ToString of the enum     return enumerationValue.ToString(); } 
like image 198
Ray Booysen Avatar answered Oct 02 '22 18:10

Ray Booysen