Enum.GetValues ​​(typeof (....)) without returning the correct enum values

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 used with typeof(Enum1) ), returns A, B:

 foreach (Enum2 e in Enum.GetValues(typeof(Enum1))) { Console.WriteLine(e); } 

Why is this?

+6
source share
7 answers

Because under the covers Enums are only ints - the second returns the values ​​of Enum1 , but in reality these values ​​are just 0 and 1 . When you add these values ​​to the Enum2 type, they are still valid and correspond to the values ​​"A" and "B".

+9
source

Since the values ​​of your enums are implicitly integers:

 public enum Enum1 { ONE = 0, TWO = 1 } public enum Enum2 { A = 0, B = 1 } 

Enum1 values ​​are implicitly converted to integers, and then to Enum2 values. If you redefined Enum1 as follows:

 public enum Enum1 { ONE = 0, TWO = 1, THREE = 2, } 

... then fail will not return "A, B" because in Enum2 there is no value for the integer value 2

+8
source

When you use Enum.GetValues() , it returns the base values. When you use foreach(Type...) , it does the conversion to an enum type. Thus, although they may not be the same Enum, they have the same base values ​​that do not have casting problems.

What happens around this equivalent

 int value = Enum.GetValues(typeof(Enum2))[1]; // this isn't valid code, it more simplified Enum1 casted = (Enum1)value; 
+3
source

Enum.GetValues(typeof(Enum1)) return {0,1} and foreach will be listed in this range

+2
source

Enum1 β†’ int and int β†’ Enum2 have an implicit listing.

+1
source

I would suggest that someone like John Skeet could come here and fully explain what is going on better than me, but this code:

 foreach (Enum2 e in Enum.GetValues(typeof(Enum1))) { Console.WriteLine(e); } 

... sees all of your Enum1 values ​​as Enum2 types.

Since the enum data type is similar to the int data type, your numeric values ​​from Enum1 are used to index Enum2 .

+1
source

The reason for this is that enums are implicitly assigned to System.Int (if they are int enums, which they are by default).

Then your second foreach explicitly outputs the results from Enum.GetValues(typeof(Enum1)) to Enum2 .

0
source

Source: https://habr.com/ru/post/908724/


All Articles