1

With a generic enum

enum MyEnum
    {
        a = 0,
        b = 1,
        c = 2
    }

If you have this two pieces of code

MyEnum myEnum = 0;

and

int a = 0;
MyEnum myEnum = a;  // ERROR, I need (MyEnum)a;

Why in the first one I can implicitly convert a number into an enum while in the second example I got an error because I need a cast?

Thanks for the clarification.

Matthew
  • 149
  • 2
  • 11
  • 4
    `= 0` is handled explicitly by the compiler, you can't even write `MyEnum myEnum = 1;`. – Lasse V. Karlsen Jul 10 '20 at 08:00
  • 1
    Its the same as doing this `MyEnum myEnum = default` – TheGeneral Jul 10 '20 at 08:03
  • 1
    See [this answer](https://stackoverflow.com/a/23762585/8873143) in combination with @LasseV.Karlsen's answer – funie200 Jul 10 '20 at 08:04
  • 1
    This case is explicitly described in the [C# specification](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/conversions#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." – Lasse V. Karlsen Jul 10 '20 at 08:04
  • While the duplicate is about `0.0` vs `1.0`, the answer there answers it perfectly. – Lasse V. Karlsen Jul 10 '20 at 08:05

0 Answers0