0

Could you explain in a detailed manner why the expected result is not correct? As most of the readers expect that the output is Byte Char Int Byte, but of course it is not the correct answer.

using System;

class Tester {

    public static string test(byte b) {
        return "Byte ";
    }

    public static string test(char c) {
        return "Char ";
    }

    public static string test(int i) {
        return "Int ";
    }

    public static void Main(String[] args) {
        byte b = 0;
        char c = 'A';
        Console.Write(test(true  ? b : c));
        Console.Write(test(false ? b : c));
        Console.Write(test(true  ? 0 : 'A'));
        Console.Write(test(false ? 'A' : (byte)0));
    }
}

The correct result is Int Int Int Int.

  • 3
    Because char and byte aren't the same type, it tries the best and converts both "up" to an int so it can process your ternary operator which requires the same type for both results. – Ray Apr 28 '22 at 20:15
  • 1
    Could you please clarify "As most of the readers expect that the output is Byte Char Int Byte"? I.e. why it is "obvious" that `...? (byte)0 : (char)0` will have type `byte`? – Alexei Levenkov Apr 28 '22 at 20:17
  • @Ray why not to byte or to char instead of int? – Soner from The Ottoman Empire Apr 28 '22 at 20:23
  • 2
    Because either requires an explicit cast, whereas both can be converted to int implicitly? – GSerg Apr 28 '22 at 20:33
  • 1
    As for why that is so, probably see https://stackoverflow.com/a/1504959/11683, https://stackoverflow.com/q/941584/11683 and https://stackoverflow.com/q/16851809/11683. – GSerg Apr 28 '22 at 20:40

0 Answers0