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 ?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With