Method overload resolution unexpected behavior

Yes – the constant 0 is implicitly convertible to any enum type. The constant 1 is only explicitly convertible to the enum type. Both are implicitly convertible to object (via boxing) but the conversion to the enum is preferred where it’s available.

Note that this has nothing to do with what values the enum defines. The conversion for any non-zero value is explicit whether it matches a value in the enum or not. It’s just a special case for the value 0, which makes some other code simpler (particularly when dealing with flags). I don’t have the spec on hand to find the reference, I’m afraid.

Bonus strangeness: due to a bug in the MS compiler (never to be fixed – it would break backward compatibility) it’s actually various zero constants, not just an integer. So Execute(0d) and Execute(0m) will convert a double and a decimal to the enum too. It doesn’t work for every zero constant – it depends on the exact nature of the source code. It’s all very odd – follow the link where Eric Lippert reveals all…

Leave a Comment