Mika H Mika H - 1 year ago 123
C# Question

C# Enum requires cast in ternary?

Today I was doing another Codegolf challenge over at Codegolf StackExchange, and I tried to do this:

SomeEnum = SomeCondition ? 1 : 2;


but this tells me
Cannot convert source type 'int' to target type 'SomeEnum'
, so I tried this instead:

SomeEnum = SomeCondition ? (SomeEnum)1 : (SomeEnum)2;


Which then solved my problem, but to my surprise the first cast here is said to be redundant. My question is: Why do I only need to cast the last integer to
SomeEnum
?

Answer Source

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 0, not 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...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download