C# enum - why does *implicit* casting from 0 work?

2020-02-07 01:22发布

问题:

Take this bit of code:

enum En {
    val1,
    val2,
}

void Main()
{
    En plop = 1;  //error: Cannot implicitly convert type 'int' to 'En'
    En woop = 0;  //no error
}

Of course it fails when assigning 1 to an enum-type variable. (Slap an explicit cast and it'll work.)

My question is: why does it NOT fail when assigning 0 ?

回答1:

It's this way because that's what the spec says...

This is another reason why it's always a good idea to give all your enums an item with value 0, 'cos you're likely to get them with that value sometimes.


The appropriate section in the C# language spec 6.1.3:

6.1.3 Implicit enumeration conversions

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. In the latter case the conversion is evaluated by converting to the underlying enum-type and wrapping the result (§4.1.10).

As to why it's that way - well, I guess only someone on the language committee that decides these things would know.

In fact, we do have something like that if you look at rawling's comment to the original question.



回答2:

The reason you can only implicitly use 0 is because 0 will always be a valid enum type where 1,2,3 or any other number might not necessarily be a valid type. For example try this

enum En {
val1=1,
val2=2,
}

0 is still a valid enum type because 0 is the default no matter what you do. Which means if you do not let one of your values be equal to 0 it will generate a 0 enum type for you.