Today I was doing another Codegolf challenge over at Codegolf StackExchange, and I tried to do this:
SomeEnum = SomeCondition ? 1 : 2;
Cannot convert source type 'int' to target type 'SomeEnum'
SomeEnum = SomeCondition ? (SomeEnum)1 : (SomeEnum)2;
The rules for the conditional operator are (C# Spec 7.14):
• If x has type X and y has type Y then o If an implicit conversion (§6.1) exists from X to Y, but not from Y to X, then Y is the type of the conditional expression. o If an implicit conversion (§6.1) exists from Y to X, but not from X to Y, then X is the type of the conditional expression. o Otherwise, no expression type can be determined, and a compile-time error occurs.
In general, there is no implicit conversion in either direction between enums and ints.
So, why is your code working? Because in your actual code, the first value is
1. And so we get the one case where an integer can be implicitly converted to an enum (C# Spec 6.1.3):
An implicit enumeration conversion permits the decimal-integer-literal 0 to be converted to any enum-type and to any nullable-type whose underlying type is an enum-type...