Question

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.

Was it helpful?

Solution 2

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";
    }

OTHER TIPS

This is because....

true.ToString() == "True"

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

Takea look at first of all: Why does Boolean.ToString output "True" and not "true"

There is no String.Concat(string, int, bool) overload, that's why your code calls nearest overload which is String.Concat(object, object, object).

And String.Concat(Object arg0, Object arg1, Object arg2) method implemented like this;

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());
}

As you can see, all objects convert to string at the last line.

That's why your code works like this;

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

And it will be;

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

And result will be;

Answer42True

true is not a string. The framework must convert true or false into strings before concatenating them to the string, and it just so happens that the way that conversion is defined for them is that the first letter is capitalized.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top