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.
This is because....
true.ToString() == "True"
And String.Concat
must convert its arguments to strings, while true
is a bool!
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";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With