1

From C# 5.0 Specification

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

Does "the decimal-integer-literal 0" mean the integer value 0?

If yes, why does an implicit enumeration conversion not permit other integer values such as 1, 2, 3, ... to be converted to any enum-type?

Thanks.

Tim
  • 1
  • 141
  • 372
  • 590
  • 2
    Eric's answer [here](https://stackoverflow.com/a/14238286/15498) seems a good one – Damien_The_Unbeliever Jun 08 '17 at 14:30
  • "Does "the decimal-integer-literal 0" mean the integer value 0?" it means a _literal zero value_, namely `0`. So not a _variable_ that could have a zero value. The other question is a duplicate. – D Stanley Jun 08 '17 at 14:30
  • @DStanley - the dupe you linked seems the opposite direction to what's asked here. I think they were asking why the zero conversion is limited to only 0. – Damien_The_Unbeliever Jun 08 '17 at 14:32
  • @Damien_The_Unbeliever Fair enough. I'll reopen. – D Stanley Jun 08 '17 at 14:33
  • https://stackoverflow.com/questions/14950750/why-switch-for-enum-accepts-implicit-conversion-to-0-but-no-for-any-other-intege? – CodeCaster Jun 08 '17 at 14:39
  • From Eric's answer in the marked duplicate: _"the reason for allowing zeros to convert to any enum is to ensure that it is always possible to zero out a "flags" enum"_. In other words, ideally _no_ literal value would be implicitly convertible, but there were those on the design team who decided they wanted to be able to "zero-out" an enum type variable and allow that literal as a special case. – Peter Duniho Jun 08 '17 at 18:03

1 Answers1

-1

Yes, it means the literal 0. For example:

static void Main()
{
   Method(0);
}

static void Method(DayOfWeek dow)
{
  Console.WriteLine(dow);
}

should print Sunday to the console. If you change 0 into 1, the program is illegal (compile-time error).

Only the (compile-time constant) zero has an implicit conversion to the enum type. For other values, you need an explicit cast instead, as in Method((DayOfWeek)1);.

Edit: This explains how the rules are. If you want to know why they chose those rules, I recommend the links in the comments (to your question above) by Damien_The_Unbeliever and CodeCaster.

Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181