Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 294
Kramii Avatar asked Jan 12 '11 11:01

Kramii


People also ask

What is the difference between concat and concatenation operator?

concat() method takes only one argument of string and concatenates it with other string. + operator takes any number of arguments and concatenates all the strings.

What can I use instead of string concatenation?

format() is more than just concatenating strings. For example, you can display numbers in a specific locale using String. format() .

What are the benefits of using the .format method instead of string concatenation?

The main advantages of using format(…) are that the string can be a bit easier to produce and read as in particular in the second example, and that we don't have to explicitly convert all non-string variables to strings with str(…).

How do you solve format specifiers should be used instead of string concatenation?

Instead of concatenating the string with + (in "Error in x file :",+ e. getMessage() ), you can use String. format to build the string instead: Logger.


1 Answers

Concerning speed it almost always doesn't matter.

var answer = "Use what makes " + "the code most easy " + "to read";
like image 171
Jonas Elfström Avatar answered Oct 06 '22 02:10

Jonas Elfström