Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# enum - why does *implicit* casting from 0 work? [duplicate]

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 ?

like image 802
Cristian Diaconescu Avatar asked Jun 06 '13 11:06

Cristian Diaconescu


People also ask

What C is used for?

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 ...

What is C language?

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.

Is C language easy?

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.

What is C full form?

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'.


1 Answers

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.

like image 55
Matthew Watson Avatar answered Oct 18 '22 12:10

Matthew Watson