5

Try this minimal code:

void Main()
{
    Foo test;
    test = 0;
    test = 1;
    Console.WriteLine(test);
}

enum Foo { Bar, Baz }

The line test = 1 will throw a compilation error, however the line test = 0 is happily compiled!

CS0266 Cannot implicitly convert type 'int' to 'UserQuery.Foo'. An explicit conversion exists (are you missing a cast?)

Compiler version: Microsoft (R) Visual C# Compiler version 1.0.0.50618

Why can I only assign a value of zero? Shouldn't it be a missing cast error in either case?

Sklivvz
  • 30,601
  • 24
  • 116
  • 172
  • 3
    The default for an enum is 0(even if that is not a valid value for that enum).Other values must be casted: `test=(Foo)1;` – Tim Schmelter Oct 26 '15 at 11:59
  • Because the language specification specifically calls out 0 as a special case that is allowed? – Damien_The_Unbeliever Oct 26 '15 at 11:59
  • @Damien_The_Unbeliever link? – m0sa Oct 26 '15 at 12:00
  • 3
    See http://stackoverflow.com/questions/14950750/why-switch-for-enum-accepts-implicit-conversion-to-0-but-no-for-any-other-intege – PaulF Oct 26 '15 at 12:00
  • 7
    @m0sa - [download the language spec](https://www.microsoft.com/en-us/download/details.aspx?id=7029). You'll be wanting section 6.1.3 (Implicit enumeration conversions) – Damien_The_Unbeliever Oct 26 '15 at 12:02
  • This behaviour is by design for two interesting reasons: 1) to fix a compiler bug, 2) to ensure that you can always zero out a "flags" enum. http://stackoverflow.com/questions/14224465/compiler-value-type-resolution-and-hardcoded-0-integer-values/14238286#14238286 – Tim Schmelter Oct 26 '15 at 12:12

0 Answers0