When s2 data type is StringBuilder no need for ToString() method but when s3 data type is string there is need for ToString() method. Is there any explanation for this? Problem is highlighted.
using System;
using System.Text;
class Program
{
static void Main(string[] args)
{
string s1 = "string1 ";
StringBuilder s2 = new StringBuilder("string1 ").Append(s1);
Console.WriteLine(s2);//string1 string1
string s3 = new StringBuilder("string1 ").Append(s1).ToString();
Console.WriteLine(s3);//string1 string1
Console.ReadKey();
}
}
StringBuilder/string
2 Answers
Know the answer? Post it. Somebody with the same question will find it here.

VulpesRank #55 · 29.2K reputationPosted Jul 31, 2013, 11:33 AM EDT
http://msdn.microsoft.com/en-us/library/system.console.writeline(v=vs.100).aspx
This line:
Console.WriteLine(s2);
is using the overload which takes a System.Object parameter. This overload automatically calls the ToString() method of whatever instance is passed to it. So, in this case, it calls StringBuilder's ToString() method which, of course, prints the string which it contains to the console.
This line:
Console.WriteLine(s3);
is using the overload which takes a string parameter and this, of course, simply prints the string to the console.
So, in the first case, ToString() is called implicitly by Console.WriteLine and, in the second case, it's called explicitly by the preceding line.
Posted Jul 31, 2013, 11:50 AM EDT