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.
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.
format() is more than just concatenating strings. For example, you can display numbers in a specific locale using String. format() .
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(…).
Instead of concatenating the string with + (in "Error in x file :",+ e. getMessage() ), you can use String. format to build the string instead: Logger.
Concerning speed it almost always doesn't matter.
var answer = "Use what makes " + "the code most easy " + "to read";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With