Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I assign an int to an enum only when it is zero? [duplicate]

There is an:

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

Now 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't 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 only implicit conversion exists for 0?

like image 364
Ryszard Dżegan Avatar asked Nov 22 '22 01:11

Ryszard Dżegan


1 Answers

From ECMA-334 (C# Language Specification)

13.1.3 Implicit enumeration conversions

An implicit enumeration conversion permits the decimal-integer-literal 0 to be converted to any enum-type.

enum's default value is 0 and at compile time it is known that is why it is allowed in the switch statement. For value other than 0, it can't be determine at compile time whether this value will exist in the enum or not.

enum (C# Reference)

Assigning additional values new versions of enums, or changing the values of the enum members in a new version, can cause problems for dependant source code. It is often the case that enum values are used in switch statements, and if additional elements have been added to the enum type, the test for default values can return true unexpectedly.

like image 68
Habib Avatar answered Feb 16 '23 20:02

Habib