0

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 ?

Shachaf.Gortler
  • 5,655
  • 14
  • 43
  • 71
  • 2
    [StringBuilder.AppendFormat](https://msdn.microsoft.com/en-us/library/system.text.stringbuilder.appendformat%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396) – 001 May 18 '16 at 17:01

3 Answers3

2

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(...);
Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343
0

In C# 6 you can use string interpolation:

var stringbuilder = new StringBuilder($"string{_variable}another string");
Matt Rowland
  • 4,575
  • 4
  • 25
  • 34
0

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)
Ilya Chernomordik
  • 27,817
  • 27
  • 121
  • 207