Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
like image 528
lojol Avatar asked Dec 06 '22 23:12

lojol


2 Answers

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)
like image 80
Jon Skeet Avatar answered Dec 27 '22 09:12

Jon Skeet


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).

like image 29
Marc Gravell Avatar answered Dec 27 '22 07:12

Marc Gravell