Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use enum item name which contains space? [duplicate]

Tags:

c#

.net

oop

enums

How to use enum item name which contains space?

enum Coolness
{
    Not So Cool = 1,
    VeryCool = 2,
    Supercool = 3
}

I am getting the Enum item name by below code

string enumText = ((Coolness)1).ToString()

I don't wont to change this code but above code should return Not So Cool. Is there any use of oops concept to make this happen? Here I don't want to change retrieving statement.

like image 630
Surendra Avatar asked Dec 15 '22 11:12

Surendra


2 Answers

Use Display attributes:

enum Coolness : byte
{
    [Display(Name = "Not So Cool")]
    NotSoCool = 1,
    VeryCool = 2,
    Supercool = 3
}

You can use this helper to get the DisplayName

public static string GetDisplayValue(T value)
{
    var fieldInfo = value.GetType().GetField(value.ToString());

    var descriptionAttributes = fieldInfo.GetCustomAttributes(
        typeof(DisplayAttribute), false) as DisplayAttribute[];

    if (descriptionAttributes == null) return string.Empty;
    return (descriptionAttributes.Length > 0) ? descriptionAttributes[0].Name : value.ToString();
}

(Credit to Hrvoje Stanisic for the Helper)

like image 193
Jamie Rees Avatar answered Dec 16 '22 23:12

Jamie Rees


Avoid space on your enum

enum Coolness : int
{
    NotSoCool = 1,
    VeryCool = 2,
    Supercool = 3
}

To get the value in text, try this:

string enumText = ((Coolness)1).ToString()

If you want a friendly description for each item of enum, try using the Description attribute, for sample:

enum Coolness : int
{
    [Description("Not So Cool")]
    NotSoCool = 1,

    [Description("Very Cool")]
    VeryCool = 2,

    [Description("Super Cool")]
    Supercool = 3
}

And to read this attribute, you could use a method like this:

public class EnumHelper
{
    public static string GetDescription(Enum @enum)
    {
        if (@enum == null)
            return null;

        string description = @enum.ToString();

        try
        {
            FieldInfo fi = @enum.GetType().GetField(@enum.ToString());

            DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

            if (attributes.Length > 0)
                description = attributes[0].Description;
        }
        catch
        {
        }

        return description;
    }
}

And use it:

string text = EnumHelper.GetDescription(Coolness.SuperCool);
like image 33
Felipe Oriani Avatar answered Dec 17 '22 00:12

Felipe Oriani