Why does String.Concat return “True” instead of “true” (same with false)?

I study boxing and unpacking 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 expand the depth of knowledge, and I found the MSDN article: Boxing and Unboxing (C # Programming Guide) , on this I found this sample code (obviously not essentially related to the main theme):

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

After execution returns:

Answer42True

Why does this happen with the literal "true" (the same thing happens with "false")?

Execution test .

Thanks in advance.

+4
4

, String.Concat() mscorlib.dll -

      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() , string.Concat,

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

, ....

true.ToString() == "True"

String.Concat , true - bool!

+5

Takea : Boolean.ToString "True" ""

String.Concat(string, int, bool), , String.Concat(object, object, object).

String.Concat(Object arg0, Object arg1, Object arg2), :

public static String Concat(Object arg0, Object arg1, Object arg2)
{
        if (arg0 == null)
        {
            arg0 = String.Empty;
        }

        if (arg1==null) {
            arg1 = String.Empty;
        }

        if (arg2==null) {
            arg2 = String.Empty;
        }

        return Concat(arg0.ToString(), arg1.ToString(), arg2.ToString());
}

, .

This is why your code works like this:

String.Concat("Answer", 42.ToString(), true.ToString()));

And it will be:

String.Concat("Answer", "42", "True"));

And the result will be:

Answer42True
+3
source

truenot a string. The Framework must convert trueeither falseto strings before concatenating them with a string, and it so happens that the way of converting them is determined by the fact that the first letter has capital letters.

+2
source

Source: https://habr.com/ru/post/1529583/


All Articles