I want to have an enum as in:
enum FilterType
{
Rigid = "Rigid",
SoftGlow = "Soft / Glow",
Ghost = "Ghost",
}
How to achieve this? Is there a better way to do this? It's gonna be used for an instance of an object where it's gonna be serialized/deserialized. It's also gonna populate a dropdownlist.
using System.ComponentModel;
enum FilterType
{
[Description("Rigid")]
Rigid,
[Description("Soft / Glow")]
SoftGlow,
[Description("Ghost")]
Ghost ,
}
You can get the value out like this
public static String GetEnumerationDescription(Enum e)
{
Type type = e.GetType();
FieldInfo fieldInfo = type.GetField(e.ToString());
DescriptionAttribute[] da = (DescriptionAttribute[])(fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false));
if (da.Length > 0)
{
return da[0].Description;
}
return e.ToString();
}
No, but if you want to scope "const" strings and use them like an enum, here's what I do:
public static class FilterType
{
public const string Rigid = "Rigid";
public const string SoftGlow = "Soft / Glow";
public const string Ghost ="Ghost";
}
If you're comfortable with extension methods, you can easily do what you're after:
//Can return string constants, the results of a Database call,
//or anything else you need to do to get the correct value
//(for localization, for example)
public static string EnumValue(this MyEnum e) {
switch (e) {
case MyEnum.First:
return "First Friendly Value";
case MyEnum.Second:
return "Second Friendly Value";
case MyEnum.Third:
return "Third Friendly Value";
}
return "Horrible Failure!!";
}
This way you can do:
Private MyEnum value = MyEnum.First;
Console.WriteLine(value.EnumValue());
No, but you can cheat like this:
public enum FilterType{
Rigid,
SoftGlow,
Ghost
}
And then when you need their string values you can just do FilterType.Rigid.ToString()
.
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