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 ?

1

3 Answers 3

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(...);
Sign up to request clarification or add additional context in comments.

Comments

0

In C# 6 you can use string interpolation:

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

3 Comments

Or in < C# 6 you can use string.Format.
@KennethK. yes but the question stated specifically about no liking the mismatch
Perhaps, but using string.Format at least cleans up the string literal to be one string rather than 3+ strings.
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.