-
Why is an explicit cast needed when assigning an enum value to a variable of its underlying integral type? enum Color { Red, Green }
enum Animal : byte { Fish, Ape }
int color = Color.Red; // CS0266
byte animal = Animal.Ape; // CS0266 This feels like a weird unnecessary limitation which is most likely caused by old design choices. But wouldn't it be possible to just allow this? I mean the compiler could just add the explicit cast under the hood itself. The whole working with enum values is much too complicated imo. For example flag enums are often used in binary data formats and therefore are often serialized as integral types like bytes. It is really a pain in the ... to add all those explicit casts even though the compiler totally knows the integral types at play. I mean the compiler can do all the checks for integral types but fails for enums which are basically named integral values. Did I miss something? Is it planned to improved something in the field of enums in the near future? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 41 replies
-
Enums aren't supposed to be treated as raw values of the underlying type and I don't think it's worth making it easier to accidentally to do in order to remove an explicit cast from the uncommon use cases such as binary serialization. |
Beta Was this translation helpful? Give feedback.
-
What do you mean by "accidentally"? Do you have an example where you could do this accidentally in a way that is somewhat harmful or leads to logical errors? The binary serialization was just an example. It isn't by far the only place where you would assign an integral value to an enum or vice versa. In the current state of possibilities I even am forced to store enum values in some integral type when I have to perform some advanced logic on them. Is the purpose of the underlying type solely the limitation of the possible values? |
Beta Was this translation helpful? Give feedback.
Enums aren't supposed to be treated as raw values of the underlying type and I don't think it's worth making it easier to accidentally to do in order to remove an explicit cast from the uncommon use cases such as binary serialization.