Search code examples
c#ternary

I'm doing some coding interview practice questions and I don't know why the answer to this problem is 65, 65


public class Program
    {      
      public static void Main(string[] args)
        {
          char x = 'A';
           int i = 0;
          Console.WriteLine (true  ? x : 0);
          Console.WriteLine(false ? i : x); 
        }
    }

I can't find anything on google, someone please shed some light on why the output is 65,65


Solution

  • Because you can implicitly convert char to int but not the other way arround so the int type wins and sets the type of the result.

    If it was the other way around you would get 'A' as the result.

    Details https://stackoverflow.com/a/220268/11869962).

            int intVar = '1';       //ok
            char charVar = (char)1; //ok
            char charVarError = 1;  //error