Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If StringBuilder is mutable, then why do StringBuilder methods return a StringBuilder object?

Tags:

c#

.net

vb.net

We all know that strings are immutable and StringBuilder is mutable. Right. Then why does its methods returns a StringBuilder object. Should they all not be void methods?

Why this

public StringBuilder Append(bool value)

and not

public void Append(bool value)

Any example explaining use of this would be great.

like image 613
Nikhil Agrawal Avatar asked Sep 07 '12 11:09

Nikhil Agrawal


1 Answers

It's called a "fluent interface". It allows you to chain together calls by repeated dot notations.

return new StringBuilder()
  .Append("Hello, ")
  .Append("world!")
  .ToString();
like image 158
duffymo Avatar answered Sep 21 '22 13:09

duffymo