Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 704
InfZero Avatar asked Dec 08 '22 09:12

InfZero


2 Answers

This is because....

true.ToString() == "True"

And String.Concat must convert its arguments to strings, while true is a bool!

like image 132
Ant P Avatar answered Dec 11 '22 09:12

Ant P


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";
    }
like image 37
BRAHIM Kamel Avatar answered Dec 11 '22 08:12

BRAHIM Kamel