MSDN says we need to convert StringBuilder
object to string
, but StringBuilder
works fine?
Why should we convert?
string[] spellings = { "hi", "hiii", "hiae" };
StringBuilder Builder = new StringBuilder();
int counter = 1;
foreach (string value in spellings)
{
Builder.AppendFormat("({0}) Which is Right spelling? {1}", counter, value);
Builder.AppendLine();
counter++;
}
Console.WriteLine(Builder); // Works Perfectly
//Why should i use tostring like below
Console.WriteLine(Builder.ToString());
// Does it make any difference in above two ways.
Console.ReadLine();
These two calls use different Console.WriteLine
overloads: WriteLine(Object)
and WriteLine(String)
.
And the WriteLine(object)
overload calls "... the ToString method of value is called to produce its string representation, and the resulting string is written to the standard output stream." (msdn)
Edit
The only difference here I can see is:
StringBuilder sb = null;
Console.WriteLine(sb); // prints terminator
Console.WriteLine(sb.ToString()); // throws NullReferenceException
In that specific example, both work fine, because Console.WriteLine
will call the ToString()
for you, on anything you pass it. The following also works:
Console.WriteLine(3); //called with an int;
Console.WriteLine(DateTime.Now);
Console.WriteLine(new {}); //called with an object
However, since the StringBuilder
is not a string, (but an object that can make a string for you), you cannot pass it to a method that expects a string, i.e.
public void PrintMe(string value)
{
Console.WriteLine(value);
}
StringBuilder sb = new StringBuilder();
PrintMe(sb); // this will not work
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