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

424 views Asked by At

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

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

And once I add +1 to byte it is not

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

There are 2 answers

3
Jon Skeet On BEST ANSWER

It's definitely not ambiguous when you use x+1 as the type of the first argument is then int. (There's no byte+byte operator in C#.)

In the first case, you have a byte argument which can be implicitly converted to an int, but then an integer literal argument. The argument is of type int, but with an implicit constant expression conversion to byte (see section 6.1.9). So while both Min(byte, byte) and Min(int, int) are applicable overloads, each is "preferred" for a different parameter (due to the conversions available), hence the ambiguity.

Note that if you have a "normal" expression of type int (as opposed to a constant expression) the ambiguity goes away:

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

Likewise a normal 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 either way:

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)
0
Marc Gravell On

I assume in the first case it can't choose between Min(byte,byte) and Min(int,int).

Operations on byte always result in an int, so x+1 is int and there is no ambiguity - it has to choose Min(int,int).