I don't know how to do this
I want code like following
enum myenum
{
name1 = "abc",
name2 = "xyz"
}
and check it
if (myenum.name1 == variable)
how can I do those things?
thanx.
This can be accomplished easily by using the DescriptionAttribute class. Originally, I was using code like the following to set the string value based on the value of an enum, but it seemed too cumbersome and had to be used everytime I wanted to parse an enum.
There are two ways to convert an Enum to String in Java, first by using the name() method of Enum which is an implicit method and available to all Enum, and second by using toString() method.
ToString() Converts the value of this instance to its equivalent string representation.
Enum constants can only be of ordinal types ( int by default), so you can't have string constants in enums.
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")...
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