Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum 0 value inconsistency

Tags:

c#

c#-4.0

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 ?

like image 803
Moe Sisko Avatar asked Feb 16 '12 03:02

Moe Sisko


People also ask

Should enums start at 0?

Enum ValuesThe first member of an enum will be 0, and the value of each successive enum member is increased by 1. You can assign different values to enum member. A change in the default value of an enum member will automatically assign incremental values to the other members sequentially.

Should enums have default value?

The default value for an enum is zero. If an enum does not define an item with a value of zero, its default value will be zero.

What is the default value for enum variable?

The default value of an enumeration type E is the value produced by expression (E)0 , even if zero doesn't have the corresponding enum member.


1 Answers

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.

like image 191
Cody Gray Avatar answered Nov 15 '22 21:11

Cody Gray