Dariusz Dariusz - 1 year ago 65
C# Question

What's the best practice way to convert enum to string?

I have enum like this:

public enum ObectTypes

then I need to convert this enum to string. Now Im doing this that way:

public string ConvertToCustomTypeName(ObjectTypes typeObj)
string result = string.Empty;
switch (typeObj)
case ObjectTypes.TypeOne: result = "This is type T123"; break;
case ObjectTypes.TypeTwo: result = "Oh man! This is type T234"; break;
case ObjectTypes.TypeTwenty: result = "This is type last"; break;

return result;

Im quite sure that there is better way do do this, Im looking for some good practice solution.

EDIT: There is no one pattern in result string.

Thanks in advance.

Answer Source

I use the [Description] attribute from System.ComponentModel


public enum RoleType
    [Description("Allows access to public information")] Guest = 0,
    [Description("Allows access to the blog")] BlogReader = 4,

Then to read from it I do

public static string ReadDescription<T>(T enumMember)
    var type = typeof (T);

    var fi = type.GetField(enumMember.ToString());
    var attributes = (DescriptionAttribute[]) 
            fi.GetCustomAttributes(typeof (DescriptionAttribute), false);
    return attributes.Length > 0 ? 
        attributes[0].Description : 

Then usage


Note: this solution assumes a single culture application as nothing was specifically asked about multiple cultures. If you are in a situation that you need to handle multiple cultures I would use the DescriptionAttribute or similar to store a key to a culture aware resource file. While you could store the enum member directly in the .resx file that would create the tightest coupling possible. I see no reason why you would want to couple the internal workings of your application (the enum member names) to key values that exist for internationalization purposes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download