Why does the switch for listing accept an implicit conversion to 0, but not for any other integer?

Exist:

enum SomeEnum { A = 0, B = 1, C = 2 } 

Now the compiler allows me to write:

 SomeEnum x = SomeEnum.A; switch(x) { case 0: // <--- Considered SomeEnum.A break; case SomeEnum.B: break; case SomeEnum.C: break; default: break; } 

0 is considered SomeItems.A . But I can not write:

 SomeEnum x = SomeEnum.A; switch(x) { case 0: break; case 1: // <--- Here is a compilation error. break; case SomeEnum.C: break; default: break; } 

Why is there only an implicit conversion for 0 ?

+20
enums c # switch-statement
Feb 19 '13 at 5:52
source share
2 answers

From ECMA-334 (C # Language Specification)

13.1.3. Implicit enumeration conversions

Implicit conversion of enumerations allows a decimal literal 0 to be converted to any type of enumeration.

the default enum value is 0 , and at compile time it is known that this is allowed in the switch statement. For a value other than 0 , at compile time it cannot be determined whether this value will exist in the enumeration or not.

enum (C # link)

Assigning additional values ​​to new versions of enumerations or changing the values ​​of enumeration members in a new version can cause problems for dependent source code. It is often the case that enumerated values are used in switch statements, and if additional elements are added to the enumeration type, checking the default values ​​may return true unexpectedly.

+15
Feb 19 '13 at 5:56 on
source share

I would also add that syntax with 0 instead of the exact enum in the switch can become error prone. Consider the following code:

 enum TestEnum { NA = 0, A } 

and then

 var e = TestEnum.NA; switch(e) { case 0: { break; } case TestEnum.A: { break; } } 

It compiles and works well. However, if for some reason the enum declaration changes to

 enum TestEnum { NA = 1, A } 

everything will break.

Although in most situations, the default value for enum is 0 , and for this reason this syntax may occur, I would use the exact enum .

+2
Feb 19 '13 at 6:09 on
source share



All Articles