Why are operations between different enum types allowed in another enum declaration but not elsewhere?
.net, c#, enums
Solution
It is actually not in the spec as far as I can tell. There is something related:
If the declaration of the enum member has a constant-expression initializer, the value of that constant expression, implicitly converted to the underlying type of the enum, is the associated value of the enum member.
Although `VerticalAnchors.Top & HorizontalAnchors.Lef` has type `VerticalAnchors` it can be implicitly converted to `VisualAnchors`. But this does not explain why the constant expression itself supports implicit conversions everywhere.
Actually, it appears explicitly to be against the spec:
The compile-time evaluation of constant expressions uses the same rules as run-time evaluation of non-constant expressions, except that where run-time evaluation would have thrown an exception, compile-time evaluation causes a compile-time error to occur.
If I didn't miss something, the spec not only does not allows this explicitly, it disallows it. Under that assumption it would be a compiler bug.
Problem
The C# compiler allows operations between different enum types in another enum type declaration, like this: ``` public enum VerticalAnchors { Top=1, Mid=2, Bot=4 } public enum HorizontalAnchors { Lef=8, Mid=16, Rig=32 } public enum VisualAnchors { TopLef = VerticalAnchors.Top | HorizontalAnchors.Lef, TopMid = VerticalAnchors.Top | HorizontalAnchors.Mid, TopRig = VerticalAnchors.Top | HorizontalAnchors.Rig, MidLef = VerticalAnchors.Mid | HorizontalAnchors.Lef, MidMid = VerticalAnchors.Mid | HorizontalAnchors.Mid, MidRig = VerticalAnchors.Mid | HorizontalAnchors.Rig, BotLef = VerticalAnchors.Bot | HorizontalAnchors.Lef, BotMid = VerticalAnchors.Bot | HorizontalAnchors.Mid, BotRig = VerticalAnchors.Bot | HorizontalAnchors.Rig } ``` but forbids them inside method code, i.e. the operation: ``` VerticalAnchors.Top | HorizontalAnchors.Lef; ``` Is flagged with this error: Operator '|' cannot be applied to operands of type 'VerticalAnchors' and 'HorizontalAnchors'. There's a workaround, of course: ``` (int)VerticalAnchors.Top | (int)HorizontalAnchors.Lef ``` I am curious about this compiler behaviour. Why are operations between different enum types allowed in another enum declaration but not elsewhere?