Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum.GetValues(typeof(....)) not returning the proper enum values

Tags:

c#

enums

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?

like image 299
JohnDoDo Avatar asked Feb 17 '12 16:02

JohnDoDo


2 Answers

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".

like image 70
Justin Avatar answered Oct 20 '22 18:10

Justin


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

like image 41
Chris Shain Avatar answered Oct 20 '22 18:10

Chris Shain