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?
Another alternative, not efficient but giving enum functionality is to use an attribute, like this:
And something like an extension method, here’s what I use:
Then you can call it like this:
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.