String Concatenation

There are several ways of concatenating strings. Concatenating simply means combining multiple strings into one. In C#, the simplest way to concatenate strings is by using the + operator as shown below.

string str1 = "Hello ";
string str2 = "World";
string result = str1 + str2;

Console.WriteLine(result);
Hello World

You can see that the effect of using the + operator on two string operands combines them. Also, note that if you are using the + operator when combining a string into another data type such as int, the int is automatically converted into string.

Console.WriteLine("Number of Guests: " + 100);
Number of Guests: 100

Another way of concatenating strings is by using the String.Concat static method. You can pass an infinite number of string or object arguments to this method. The program below shows you how to use this method.

string result = String.Concat("We have ", 100, " guests ", " this evening.");

Console.WriteLine(result);
We have 100 guests this evening.

You can also use the String.Join static method. It is used to combine strings stored inside a string array.

string[] words = { "Welcome", "to", "my", "site." };
string result = String.Join(" ", words);

Console.WriteLine(result);

The String.Join method accepts two arguments, the first is the string that will be inserted between each of the strings being combined. We passed a ” “ to put space between the words. The second   argument is the string array itself. Another overload of  String.Joinallows you to pass a list of strings instead of a string   array.

string result = String.Join(" ", "Welcome", "to", "my", "site.");

Console.WriteLine(result);

Combining large strings using System.String could affect performance. In .NET, all string objects are immutable. This means that once a string variable is initialized, its value cannot be changed. When you modify the value of a string, a new copy of the string is created and the old copy is discarded. Hence, all methods that process strings return a copy of the modified string – the original string remains intact. .NET provides the StringBuilder class that you can use when combining large strings.   It will be discussed in another lesson.