Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string values enum in c# [duplicate]

Tags:

c#

.net

enums

there any way to define enum in c# like below?

public enum MyEnum : string
{
    EnGb = "en-gb",
    FaIr = "fa-ir",
    ...
}

ok, according to erick approach and link, i'm using this to check valid value from provided description:

public static bool IsValidDescription(string description)
{
    var enumType = typeof(Culture);
    foreach (Enum val in Enum.GetValues(enumType))
    {
        FieldInfo fi = enumType.GetField(val.ToString());
        AmbientValueAttribute[] attributes = (AmbientValueAttribute[])fi.GetCustomAttributes(typeof(AmbientValueAttribute), false);
        AmbientValueAttribute attr = attributes[0];
        if (attr.Value.ToString() == description)
            return true;
    }
    return false;
}

any improvement?

like image 778
Sadegh Avatar asked Jun 05 '10 09:06

Sadegh


2 Answers

Another alternative, not efficient but giving enum functionality is to use an attribute, like this:

public enum MyEnum
{
  [Description("en-gb")]
  EnGb,
  [Description("fa-ir")]
  FaIr,
  ...
}

And something like an extension method, here's what I use:

public static string GetDescription<T>(this T enumerationValue) where T : struct
{
  var type = enumerationValue.GetType();
  if (!type.IsEnum) throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");
  var str = enumerationValue.ToString();
  var memberInfo = type.GetMember(str);
  if (memberInfo != null && memberInfo.Length > 0)
  {
    var attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
    if (attrs != null && attrs.Length > 0)
      return ((DescriptionAttribute) attrs[0]).Description;
  }
  return str;
}

Then you can call it like this:

MyEnum.EnGb.GetDescription()

If it has a description attribute, you get that, if it doesn't, you get the .ToString() version, e.g. "EnGb". The reason I have something like this is to use an enum type directly on a Linq-to-SQL object, yet be able to show a pretty description in the UI. I'm not sure it fits your case, but throwing it out there as an option.

like image 70
Nick Craver Avatar answered Oct 18 '22 07:10

Nick Craver


Regarding Matthew's answer, I suggest you to use Dictionary<MyEnum, String>. I use it as a static property:

class MyClass
{
    private static readonly IDictionary<MyEnum, String> dic = new Dictionary<MyEnum, String>
    {
        { MyEnum.EnGb, "en-gb" },
        { MyEnum.RuRu, "ru-ru" },
        ...
    };

    public static IDictionary<MyEnum, String> Dic { get { return dic; } }
}
like image 7
abatishchev Avatar answered Oct 18 '22 07:10

abatishchev