Consider the following piece of code:
namespace ConsoleApplication1 {
class Program {
public static void Main (string[] args) {
var en = (TestEnum)Enum.Parse(typeof(TestEnum), "AA");
Console.WriteLine(en.ToString());
Console.ReadKey();
}
}
public enum TestEnum {
AA = 0x01,
AB = 0x02,
AC = 0x03,
BA = 0x01,
BB = 0x02,
BC = 0x03
}
}
If you execute this, the variable en
will get the value of TestEnum.BA
. Now I have learned from this that enum flags should be unique, or you get these kind of unexpected things, but I do fail to understand what is happening here.
The even weirder part is that when I add the [Flags] attribute to the TestEnum, it solves the problem and returns TestEnum.AA instead of TestEnum.BA, but for the original enum (which is much larger, around ~200 members) for which I have discovered this problem this does not make a difference.
My understanding is that enums are a value type, so when you define your own flags it will store the value in memory as 0x01 in the case of for TestEnum.AA, and when you cast it from object to TestEnum it will do the lookup for that flag value and find TestEnum.BA.
This is also confirmed by running the following line:
var en = (TestEnum)(object)TestEnum.AA;
Console.WriteLine(en.ToString());
Which will output: BA
So my question is: what exactly is happening here? And more importantly why does adding the Flags attribute make a difference?