Given this code:
public enum Enum1
{
ONE,
TWO
}
public enum Enum2
{
A,
B
}
This code returns ONE, TWO:
foreach (Enum1 e in Enum.GetValues(typeof(Enum1)))
{
Console.WriteLine(e);
}
But this code, instead of failing (because Enum2 e is used with typeof(Enum1)), returns A, B:
foreach (Enum2 e in Enum.GetValues(typeof(Enum1)))
{
Console.WriteLine(e);
}
Why is that?
Because under the covers Enums are just ints – the second returns the values of
Enum1, but really those values are just0and1. When you cast those values to the typeEnum2these are still valid and correspond to the values “A” and “B”.