Since now we know the fundamentals about strings and their structure, it is time to learn about the various operations we can perform on them. The simplest of these operation is concatenation, or joining two or more strings together and obtaining a new string as a result.
We have already done this a few times, using the operators + and +=. Example:
1 2 3 |
string surname = "John "; string name = "Doe"; string completeName = surname + name; |
Another way of concatenating two strings is by using the Concat() method:
1 2 3 |
string surname = "John "; string name = "Doe"; string completeName = string.Concat(surname, name); |
Both of the above methods produce the same result.
You should know that Concat() does not apply any action on the original strings. Instead, it returns a new string, as a result. This is a common mistake that many beginner programmers encounter:
1 2 3 |
string surname = "John "; string name = "Doe"; string.Concat(surname, name); |
They believe that the method will add the second string to the first one, but instead, nothing happens. This is because the method will only return a new string which will hold the concatenated value of the original two strings, but since this returned value is not assigned to anything, it will be simply lost.
You probably already know, but I will still mention it again: concatenation allows us to join multiple data types. For instance:
1 2 3 4 |
string name = "John"; int age = 30; Console.WriteLine("Hello! My name is " + name + " and my age is " + age); |
In this case, our int variable will be first converted to a string, and then concatenated to the rest of the string. As I already explained, this can lead to errors such as this one:
1 2 3 |
int two = 2; int three = 3; Console.WriteLine("The sum of 2 + 3 is equal to " + two + three); |
Beginner programmers would expect that the two + three operation will be evaluated as a mathematical sum between the values of the two int variables. However, as we learned in the operator precedence lesson, concatenation operator has a higher priority than the mathematical addition. This means that concatenation will be done first, not the addition. This also means that the first thing that will happen will be the concatenation of the string “The sum of 2 + 3 is equal to “ with the value of the two variable, which will result still in a string, which will then be concatenated with the value of the three variable. This means we will get this result:
instead of the expected 5.