Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Enum requires cast in ternary? [duplicate]

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?

like image 443
Metoniem Avatar asked Jan 05 '23 14:01

Metoniem


1 Answers

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...

like image 153
Damien_The_Unbeliever Avatar answered Jan 11 '23 09:01

Damien_The_Unbeliever