Geek people always like to argue about several useless topics, and the StringBuilder vs StringWriter was my latest .net techy discussion. This one is really even more useless than the usual topics. Basically, we have two objects that perform exactly the same: they contat/format strings.

Why do they both exist? Well, I don't know. Based on the MSDN documentation, it seams that the StringWriter is just a facade for a StringBuilder, that implements TextWriter. And that is the reason why I prefer to use the StringWriter. StringBuilder has an alien interface, methods like Append, AppendFormat, only exist on the StringBuilder class. However, the StringWriter has all the know methods like Write, WriteLine, etc.

But the main reason isn't just the names. By using TextWriters, we can write generic code, por example, consider this method:

  1. public void WriteXml( TextWriter writer ) {}

We can now invoke it to build a memory representation (StringWriter), we can write the XML in an ASP.NET control (HtmlTextWriter) or we could just write it to Console.Out. Obviously, we could also use the StringBuilder and the write its contents to the TextWriter... but that would definitely be uglier.

So... a... this proves mathematically and without a doubt that StringWriter wins the battle.

Related Posts

One Response to “StringWriter vs StringBuilder”

  1. w Says:

    Exactly except that for xml we need to use the xmlwriter