Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to have strings for enums?

Tags:

c#

.net

enums

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.

like image 230
Joan Venge Avatar asked Oct 16 '09 17:10

Joan Venge


4 Answers

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();
}
like image 131
Shaun Bowe Avatar answered Sep 19 '22 15:09

Shaun Bowe


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";
}
like image 33
Dave Markle Avatar answered Sep 23 '22 15:09

Dave Markle


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());
like image 38
Mark Carpenter Avatar answered Sep 21 '22 15:09

Mark Carpenter


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().

like image 36
Malfist Avatar answered Sep 20 '22 15:09

Malfist