views:

195

answers:

4

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");
+8  A: 

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

Aviad P.
Wow I didn't realize this was such a good answer :) Thanks!
Aviad P.
well, you were quick and I didn't knew about 'fluent syntax' (And I'm fairly new to this site...) xD
dada686
+2  A: 

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

NetSide
A: 

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.

Greg D
A: 

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?

YotaXP
as of now i've been using both syntax, but i'm confronted in a project where I must add lots of strings to my Sb and good performance was needed, therefor my question.
dada686