I don\'t know how to do this
I want code like following
enum myenum
{
name1 = \"abc\",
name2 = \"xyz\"
}
and check it
Depending on what you want to do, maybe you could achieve the same effect by using a Dictionary instead of enum
s.
This was discuessed here before, but can't find it. Short version: you can't give enum members string values. You can use the member names as the values, but often this isn't what you want. Please follow this link for a guide how to use attributes to annotate string values to enum members.
Nice answers here. Elaborating onto the suggested answer is if you would like to rather get the enum value given the enum description. I havent tested this but this might work :
Enum :
public enum e_BootloadSource : byte
{
[EnumMember]
[Display(Name = "UART")]
[Description("UART_BL_RDY4RESET")]
UART = 1,
[EnumMember]
[Display(Name = "SD")]
[Description("SD_BL_RDY4RESET")]
SD = 2,
[EnumMember]
[Display(Name = "USB")]
[Description("USB_BL_RDY4RESET")]
USB = 3,
[EnumMember]
[Display(Name = "Fall Through Mode")]
[Description("FALL_THRGH_BL_RDY4RESET")]
FALL_THROUGH_MODE = 4,
[EnumMember]
[Display(Name = "Cancel Bootload")]
[Description("BL_CANCELED")]
CANCEL_BOOTLOAD = 5,
}
Use as follows :
foreach(e_BootloadSource BLSource in Enum.GetValues(typeof(e_BootloadSource)))
{
if (BLSource.GetDescription() == inputPieces[(int)SetBLFlagIndex.BLSource])
{
newMetadata.BootloadSource = BLSource;
}
}
Note inputpieces is purely a string array and newMetadata.BootloadSource is e_BootloadSource.
Unfortunately that's not possible. Enums can only have a basic underlying type (int
, uint
, short
, etc.). If you want to associate the enum values with additional data, apply attributes to the values (such as the DescriptionAttribute).
public static class EnumExtensions
{
public static TAttribute GetAttribute<TAttribute>(this Enum value)
where TAttribute : Attribute
{
var type = value.GetType();
var name = Enum.GetName(type, value);
return type.GetField(name)
.GetCustomAttributes(false)
.OfType<TAttribute>()
.SingleOrDefault();
}
public static String GetDescription(this Enum value)
{
var description = GetAttribute<DescriptionAttribute>(value);
return description != null ? description.Description : null;
}
}
enum MyEnum
{
[Description("abc")] Name1,
[Description("xyz")] Name2,
}
var value = MyEnum.Name1;
if (value.GetDescription() == "abc")
{
// do stuff...
}
According to here what you are doing is not possible. What you could do maybe would be to have a static class full of constants, maybe something like so:
class Constants
{
public static string name1 = "abc";
public static string name2 = "xyz";
}
...
if (Constants.name1 == "abc")...