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);
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)
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With