When should I use String.Format or String.Concat instead of the concatenation operator?

Posted by Kramii on Stack Overflow See other posts from Stack Overflow or by Kramii
Published on 2011-01-12T11:45:32Z Indexed on 2011/01/12 11:54 UTC
Read the original article Hit count: 320

Filed under:
|
|

In C# it is possible to concatenate strings in several different ways:

Using the concatenation operator:

var newString = "The answer is '" + value + "'.";

Using String.Format:

var newString = String.Format("The answer is '{0}'.", value);

Using String.Concat:

var newString = String.Concat("The answer is '", value, "'.");

What are the advantages / disadvantages of each of these methods? When should I prefer one over the others?

The question arises because of a debate between developers. One never uses String.Format for concatenation - he argues that this is for formatting strings, not for concatenation, and that is is always unreadable because the items in the string are expressed in the wrong order. The other frequently uses String.Format for concatenation, because he thinks it makes the code easier to read, especially where there are several sets of quotes involved. Both these developers also use the concatenation operator and String.Builder, too.

© Stack Overflow or respective owner

Related posts about c#

Related posts about string