What makes the Min (byte, int) call ambiguous?

I do not understand why, according to the compiler, the following is vague:

byte x = 200; int novaCervena = Math.Min(x, 10); 

And as soon as I add +1 to the byte, this is not

 byte x = 200; int novaCervena = Math.Min(x+1, 10); 
+4
source share
2 answers

This is definitely not ambiguous if you use x+1 , since the type of the first argument is then int . (There is no byte+byte operator in C #.)

In the first case, you have a byte argument, which can be implicitly converted to int , but then an integer literal. The argument is of type int , but with an implicit conversion of the constant expression to byte (see Section 6.1.9). Therefore, when both Min(byte, byte) and Min(int, int) are applicable overloads, each of them is "preferred" for the other parameter (due to the available transformations), therefore, ambiguity.

Note that if you have a β€œnormal” expression of type int (as opposed to a constant expression), the uncertainty goes away:

 byte x = 200; int y = 10; int z = Math.Min(x, y); // Uses Math.Min(int, int) 

Similarly the usual byte argument:

 byte x = 200; byte y = 10; byte z = Math.Min(x, y); // Uses Math.Min(byte, byte) 

Or you can force the conversion:

 byte x = 200; byte z = Math.Min(x, (byte)10); // Uses Math.Min(byte, byte) byte a = 200; int b = Math.Min((int) a, 10); // Uses Math.Min(int, int) 
+11
source

I assume that in the first case, he cannot choose between Min(byte,byte) and Min(int,int) .

Operations on byte always lead to int , therefore x+1 is int , and there is no ambiguity - it should choose Min(int,int) .

+4
source

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


All Articles