Why is Byte advancing to Enum?

Using an external API that has several overloads that accept different types of data but does not list, I decided to create a convenient method to give a little more type safety for the enumerations and as a result something like this turned out:

namespace TestEnumPromotion
{
    enum Values
    {
        Value0,
        Value1,
    }

    class Program
    {
        static void Main(string[] args)
        {
            // Prints int
            Overloaded(0);

            // Prints Values
            Overloaded(Values.Value0);

            // Does not compile! :-/
            Overloaded((byte) 0);

            // Prints int
            byte b = 0;
            Overloaded(b);
        }

        static void Overloaded(int i)
        {
            Console.WriteLine("int");
        }

        static void Overloaded(Values i)
        {
            Console.WriteLine("Values");
        }
    }
}

But I was very surprised to see that the code does not compile, because Overloaded((byte) 0):

The call is ambiguous between the following methods or properties: "Program.Overloaded (int)" and "Program.Overloaded (Values)"

But byteit cannot automatically increase to Values, that is, Values v = (byte)bit will not compile, because:

It is not possible to implicitly convert the type 'byte' to 'TestEnumPromotion.Values`.

So, the only possible overload should be int, right?

, , , , int, IL ILDASM , , .

.method private hidebysig static void  Overloaded(valuetype TestEnumPromotion.Values i) cil managed
{
    // Code size       13 (0xd)
    .maxstack  8
    IL_0000:  nop
    IL_0001:  ldstr      "Values"
    IL_0006:  call       void [mscorlib]System.Console::WriteLine(string)
    IL_000b:  nop
    IL_000c:  ret
} // end of method Program::Overloaded

?

+4
1

: literal 0 enum.

UPDATE: , . , . .

:

Values someValue = 1; //can not implicitly convert `int` to...

, , :

Values someValue = 0;

, (byte)0 ( ) Values int, . (byte)1 , .

, , Overloaded(0), - , ; , Overloaded(int i) .

# 4.0:

1.10 (...) - , . , , , . , 0 . (...)

+4

Source: https://habr.com/ru/post/1695173/


All Articles