3

I would like to know the difference (if there is any) between :

StringBuilder sb = new StringBuilder(); 
sb.Append("xxx");
sb.Append("yyy");
sb.Append("zzz");

And :

StringBuilder sb = new StringBuilder(); 
sb.Append("xxx")
  .Append("yyy")
  .Append("zzz");

4 Answers 4

11

There's no difference, the latter case is called 'Fluent Syntax'.

Sign up to request clarification or add additional context in comments.

1 Comment

well, you were quick and I didn't knew about 'fluent syntax' (And I'm fairly new to this site...) xD
1

There is no functional difference. In your first case, you're appending strings to the same StringBuilder in the same order in three statements. In your second case, you're appending the same strings to the same StringBuilder in one statement.

There will be no notable performance difference and absolutely no observable difference. You may choose one or the other stylistically.

Comments

1

The IL surely will look differently between the two, and just from first looks, the chained version may be a few nanoseconds faster (I just like saying nanoseconds.), but it's nothing to consider refactoring your code over. If it looks cleaner one way, I'd take that path.

It always bugged me, how StringBuilder.Append would always return itself. It causes one to think that the StringBuilder is an immutable structure, when it most definitely is not. It is also especially annoying in F#, where you have to explicitly ignore what it returns. But whatcha gonna do?

Comments

0

There is no difference between them. But you can use second one for less code line :)

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.