I have enum
[Flags]
public enum MyEnum
{
Item1 = 32768,
Item2 = 65536,
Item3 = 524288,
Item4 = Item3
}
Results of ToString() operat
No, you can't.
If multiple enumeration members have the same underlying value and you attempt to retrieve the string representation of an enumeration member's name based on its underlying value, your code should not make any assumptions about which name the method will return.
Enum.ToString() Method
No, because you set Item4
to be equal to Item3
, and as they're just typesafe ints (enums are), the CLR can't tell the difference.
Try setting Item4
to a different value to get the expected result.
Firstly, I don't understand why you need two items with the same value. However, if you need the same enum values but want the different names later, perhaps try using the DescriptionAttribute
in System.ComponentModel
?
[Flags]
public enum MyEnum
{
[DescriptionAttribute("Item1")]Item1 = 32768,
[DescriptionAttribute("Item2")]Item2 = 65536,
[DescriptionAttribute("Item3")]Item3 = 524288,
[DescriptionAttribute("Item4")]Item4 = Item3
}
Then you could this method to get the description value back:
public string ValueOf(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[]) fi.GetCustomAttributes( typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
{
return attributes[0].Description;
}
else
{
return value.ToString();
}
}
I've not actually tried this out, so the MSDN quote @MarcinJuraszek posted might still apply here.
Source: http://blog.waynehartman.com/articles/84.aspx
No, because enum
aren't collections of strings. They are value types that can contain an integral of a certain type (normally an int
), where some of these integrals are connected to a "name" (your Item4)