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
?
I would also add, that the syntax with
0
instead of the exactenum
in theswitch
statement may become error prone. Consider the following code:and then
This compiles and works well. However if for some reason,
enum
declaration changes toeverything will get broken.
Though in the majority of situations the default value for
enum
is0
and for that reason this syntax may take place, I would use the exactenum
.From ECMA-334 (C# Language Specification)
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 than0
, it can't be determine at compile time whether this value will exist in the enum or not.enum (C# Reference)