12

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 ?

7

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Can you expand on that?
I don't see how this answers the question. Default initialization has nothing to do with the compiler allowing myEnum = 0 in code. You can't assign 0 to a struct but they still get default initialized. You can't assign 0 to a bool but they still get default initialized.
@Rawling Good point, I'll admend
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.