Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: most readable string concatenation. best practice [duplicate]

Possible Duplicate:
How should I concatenate strings?

There are several ways to concat strings in everyday tasks when performance is not important.

  • result = a + ":" + b
  • result = string.Concat(a, ":", c)
  • result = string.Format("{0}:{1}", a, b);
  • StringBuilder approach
  • ... ?

what do you prefer and why if efficiency doesn't matter but you want to keep the code most readable for your taste?

like image 528
Andrew Florko Avatar asked Jul 18 '10 19:07

Andrew Florko


1 Answers

It depends on the use. When you just want to concat two strings, using a + b is just much more readable than string.Format("{0}{1}", a, b). However, it is getting more complex, I prefer using string.Format. Compare this:

string x = string.Format("-{0}- ({1})", a, b);

against:

string x = "-" + a + "- (" + b + ")";

I think that in most cases it is very easy to spot the most readable way to do things. In the cases where it is debatable which one is more readable, just pick one, because your boss isn't paying for these pointless discussions ;-)

like image 190
Steven Avatar answered Sep 19 '22 22:09

Steven