4

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);
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
lojol
  • 471
  • 1
  • 5
  • 9

2 Answers2

11

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)
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thanks, I got it. So I need to cast to int – lojol Feb 07 '11 at 07:31
  • @lojol: If you want it to use the `int` version, yes. – Jon Skeet Feb 07 '11 at 07:33
  • 1
    @lojol: You _can_ have an expression `byte + byte`, there's just no operator explicitly defined for it. The compiler will promote both operands to `int` in that case so it can use the `int + int` operator. So you can write such an expression, there's just no operator to do it directly. It's important for you to understand the distinction. – Jeff Mercado Feb 07 '11 at 08:03
4

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

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900