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.
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)
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With