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 just 0 and 1.  When you cast those values to the type Enum2 these are still valid and correspond to the values "A" and "B".
Because the values of your enums are implicitly integers:
public enum Enum1
{
    ONE = 0,
    TWO = 1
}
public enum Enum2
{
    A = 0,
    B = 1
}
The values of Enum1 are being implicitly converted to integers and then to values of Enum2. If you redefined Enum1 as follows...
public enum Enum1
{
    ONE = 0,
    TWO = 1,
    THREE = 2,
}
...then it would fail not return "A, B", because there is no value in Enum2 for the integer value 2
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