Shachaf.Gortler
Shachaf.Gortler

Reputation: 5735

String builder and String Concat

I have a piece of code that look follows this pattern ,

 var stringBuilder =new StringBuilder( string.Concat(" string", _variable, 
"another string" , _variable2 ... );

according to some logic do

stringBuilder.Append(" Some more strings"); 

I don't like The mismatch of using StringBuilder and string.Concat and I want a more elegant way of doing

What I thought was using StringBuilder.Append like so ,

StringBuilder.Append("string");
StringBuilder.Append(_variable);
StringBuilder.Append("another string");

Is there a better way then this approach ?

Upvotes: 0

Views: 135

Answers (3)

Ivan Stoev
Ivan Stoev

Reputation: 205629

Actually the StringBuilder is AFAIK the first BCL class that supports fluent syntax, so you can simply chain multiple Append / AppendLine / AppendFormat calls:

var stringBuilder = new StringBuilder()
    .Append(" string").Append(_variable)
    .Append("another string").Append(_variable2)
    .Append(...);

Upvotes: 2

Ilya Chernomordik
Ilya Chernomordik

Reputation: 30205

StringBuilder is the proper way to do a lot of string concatenation. It is specifically made for that and is optimal from performance point of view, so if you want a lot of string operations, use it. Otherwise if it's one small operation you can follow Matt Rowland advise (if you have C# 6), though you won't need StringBuilder for that at all:

string result = $"string {_variable} another string"

If you don't have C# 6, you can do:

string result = string.Format("string {0} another string", _variable)

Upvotes: 0

Matt Rowland
Matt Rowland

Reputation: 4595

In C# 6 you can use string interpolation:

var stringbuilder = new StringBuilder($"string{_variable}another string");

Upvotes: 0

Related Questions