Moe Sisko
Moe Sisko

Reputation: 12015

Enum 0 value inconsistency

Example code :

    public enum Foods
    {
        Burger,
        Pizza,
        Cake
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Eat(0);   // A
        Eat((Foods)0);  // B
        //Eat(1);  // C : won't compile : cannot convert from 'int' to 'Foods'
        Eat((Foods)1);  // D    
    }

    private void Eat(Foods food)
    {
        MessageBox.Show("eating : " + food);
    }

Code at line C won't compile, but line A compiles fine. Is there something special about an enum with 0 value that gets it special treatment in cases like this ?

Upvotes: 10

Views: 242

Answers (1)

Cody Gray
Cody Gray

Reputation: 244752

Yes, the literal 0 is implicitly convertible to any enum type and represents the default value for that type. According to the C# language specification, in particular section 1.10 on enums:

The default value of any enum type is the integral value zero converted to the enum type. In cases where variables are automatically initialized to a default value, this is the value given to variables of enum types. In order for the default value of an enum type to be easily available, the literal 0 implicitly converts to any enum type. For the default value of an enum type to be easily available, the literal 0 implicitly converts to any enum type.

Upvotes: 14

Related Questions