Though we already used the concatenator operator quite a few times, we did not explain it yet. The concatenator operator (+) is used to join values of type string together.
As a side note, it is not necessary for both operands to be of type string. If at least one of them is a string, the others will be converted to strings, in order to ensure a successful string concatenation.
You should also know that this conversion is made on the fly, by the .NET runtime. This is a wonderful thing, we don’t have to worry about converting every operand to string, etc. However, though this might seem like a tedious task, you should get yourself used to explicitly convert every operand that needs to be converted, in order to avoid implicit conversion errors (of which we will discuss in the future).
Here is a simple example of using the concatenator operator, with or without explicit casting of non-string operators:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
//simple concatenation of strings string firstName = "John"; string lastName = "Doe"; string fullName = firstName + lastName; Console.WriteLine(fullName); //concatenation without explicit conversion string greeting = "Hello! The date of today is "; int currentDate = 6; string fullGreeting = greeting + currentDate; Console.WriteLine(fullGreeting); //concatenation with explicit conversion string address = "Uknown Street, number "; int streetNumber = 3; string fullAddress = address + streetNumber.ToString(); Console.WriteLine(fullAddress); Console.Read(); |
The console output would be
The concepts explained in this lesson are also shown visually as part of the following video:
Tags: concatenator operator, operators