Search code examples
c#.netboxingunboxing

Why String.Concat returns 'True' instead of 'true' (the same with false)?


I'm studying boxing and unboxing topic from C# 5.0 in a Nutshell by Joseph Albahari and Ben Albahari. Copyright 2012 Joseph Albahari and Ben Albahari, 978-1-449-32010-2, but I need to extend the deep of knowledge and I found the MSDN article: Boxing and Unboxing (C# Programming Guide), on it I found this example code (evidently not intrinsically related to the main topic):

Console.WriteLine (String.Concat("Answer", 42, true));

Once executed it returns:

Answer42True

Why this is happening with the literal 'true' (the same occurs with 'false')?

Execution test.

Thanks in advance.


Solution

  • For the sample reason if you try to decompile String.Concat() method in mscorlib.dll you will get something like this

          for (int index = 0; index < args.Length; ++index)
          {
            object obj = args[index];
            values[index] = obj == null ? string.Empty : obj.ToString(); //which  will call the `ToString()` of `boolean struct` 
    
          }         
    

    ToString() method which is called by default by string.Concat method it is like this

     public override string ToString()
        {
          return !this ? "False" : "True";
        }