10

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 ?

Moe Sisko
  • 11,665
  • 8
  • 50
  • 80

1 Answers1

14

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.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
  • Yes. Here "0" means default. What would "1" mean? – David Schwartz Feb 16 '12 at 03:16
  • @David: Nothing. `Foods food = 1;` would not compile. However, you can *cast* any literal to an enum, so `Foods food = (Foods)1;` is just fine. – Cody Gray - on strike Feb 16 '12 at 03:18
  • Anthony is right. The reason you can implicitly convert the literal zero to any enum type is that the language designers determined it to be a useful feature and wrote it into the specification. – phoog Feb 16 '12 at 04:35