What is the use of the return value of the StringBuilder Append(string...) function?

The complete syntax of StringBuilder's Append(string s) function (and similar functions) is

StringBuilder myStringBuilder.Append(string myString)

since myStringBuilder.Append(string myString) already adds the string to myStringBuilder, I was wondering what the return value is for? I have never seen any example code that makes use of the return value.

According to msdn it does not return a new StringBuilder instance but a reference to the current builder itself (that would be myStringBuilder). I just can't think of a scenario when using the return value makes sense at all, why didn't they make the return type void?

Jon Skeet
people
quotationmark

It means you can easily chain calls together:

sb.Append("Foo=").Append(foo).Append("&Bar=").Append(bar);

... instead of using several separate statements:

sb.Append("Foo=");
sb.Append(foo);
sb.Append("&Bar=");
sb.Append(bar);

The fact that it's a single expression means you can also use it in places where you're restricted to a single expression, e.g. field initialization or a return statement. The latter means you can use it for expression-bodied members, too:

public override string ToString() =>
    new StringBuilder("x").Append(...).Append(...).ToString();

(In many cases using string.Format or an interpolated string literal would make more sense, but sometimes StringBuilder is the way forward...)

people

See more on this question at Stackoverflow