Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we should use ToString method with StringBuilder?

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();
like image 931
Registered User Avatar asked Dec 15 '22 07:12

Registered User


2 Answers

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
like image 57
MarcinJuraszek Avatar answered Dec 18 '22 10:12

MarcinJuraszek


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
like image 40
SWeko Avatar answered Dec 18 '22 10:12

SWeko