Does C # Enum require triple throw?

Today I made another Codegolf call on Codegolf StackExchange , and I tried to do this:

SomeEnum = SomeCondition ? 1 : 2;

but it 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 considered redundant. My question is: Why do I just need to highlight the last integer in SomeEnum ?

+4
source share
4 answers

Rules for the conditional statement: (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 any direction between enums and ints.

, ? 0, 1. , , (# Spec 6.1.3):

- , ...

+6

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

SomeEnum "SomeEnum". .

+3

SomeEnum, (true false) SomeEnum, int, enum #. , .

, .

0

:

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

enum enum:

SomeEnum SomeEnum = (true) ? SomeEnum.First : SomeEnum.Second;

public enum SomeEnum : byte
{
    First = 1,
    Second = 2
}

:

SomeEnum SomeEnum = (true) ? (SomeEnum)1 : 2; //THIS WON'T COMPILE!

... 0:

SomeEnum SomeEnum = (true) ? 0 : 2;
0

Source: https://habr.com/ru/post/1669026/


All Articles