Wednesday, June 19, 2019 00:43

Concatenation

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:

Another way of concatenating two strings is by using the Concat() method:

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:

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:

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:

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.

Comments

comments

Tags: ,

Leave a Reply