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 ?
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
C is an imperative procedural language supporting structured programming, lexical variable scope, and recursion, with a static type system. It was designed to be compiled to provide low-level access to memory and language constructs that map efficiently to machine instructions, all with minimal runtime support.
Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.
Full form of C is “COMPILE”. One thing which was missing in C language was further added to C++ that is 'the concept of CLASSES'.
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.
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