Joining strings with variables
Concatenation means joining strings end to end. In C# the + operator does it. It's most useful with variables, because the message can then change with the data:
string adjective = "awesome";
string message = "AlgoCademy is ";
message = message + adjective;
Console.WriteLine(message); // AlgoCademy is awesome
The right side is evaluated first: message + adjective creates a new string. Then the assignment stores that string back in message.
The += operator
Updating a variable from its own value is so common that C# has a shortcut. message += adjective; means exactly message = message + adjective;:
string adjective = "awesome";
string message = "AlgoCademy is ";
message += adjective;
Console.WriteLine(message); // AlgoCademy is awesome
You can use it as many times as you like, and with string literals as well as variables:
string name = "Andy";
string pet = "dog";
string message = "Hey, ";
message += name;
message += "! Nice ";
message += pet;
message += "!";
Console.WriteLine(message); // Hey, Andy! Nice dog!
The message grows one piece at a time.
Gotchas in C#
Strings are immutable
+= doesn't change the existing string. It builds a new one and makes the variable refer to it. Another variable that referred to the old string still holds the old text:
string s = "hi";
string t = s;
s += "!";
Console.WriteLine(t + " " + s); // hi hi!
This is harmless in a short lesson. In a loop that appends thousands of times, it creates many temporary strings, and a StringBuilder is the better tool.
Spaces are your job
+ adds nothing between the pieces. That's why "AlgoCademy is " ends with a space.
Numbers are converted, left to right
Joining a string and a number makes a string, but evaluation goes left to right. "n=" + 5 + 1 is n=51, whereas 1 + 2 + "x" is 3x, because the two numbers are added before the string appears.
The variable must exist first
+= reads the old value, so the variable has to be declared and assigned before you use it.
Why build messages this way
Programs rarely know their whole message in advance. A name comes from a user, a score from a calculation, a pet from a list. Concatenation lets the fixed parts of a message stay in literals while the changing parts come from variables. Building the message in steps with += also lets you decide, as the program runs, which pieces to add: you can append one more sentence only when a condition holds, which a later lesson on if statements will show.
Another way to build the same text
C# also has string interpolation: a string starting with $ can hold variables inside curly braces. It builds the same message from the earlier example in one expression:
string name = "Andy";
string pet = "dog";
Console.WriteLine($"Hey, {name}! Nice {pet}!"); // Hey, Andy! Nice dog!
It's often easier to read than a chain of +. This lesson practices +=, so use that in the exercise.
The exercise
The lesson starts with two variables, message holding "Coding is " and adjective holding "worthwhile". There are three steps:
- Append the adjective.
message += adjective;turnsmessageintoCoding is worthwhile. - Append the ending.
message += ", isn't it?";adds a comma and a question. The apostrophe is fine inside double quotes. NowmessageisCoding is worthwhile, isn't it?. - Print it.
Console.WriteLine(message);writes the finished text.
string message = "Coding is ";
string adjective = "worthwhile";
message += adjective;
message += ", isn't it?";
Console.WriteLine(message);
The output is:
Coding is worthwhile, isn't it?
If you want to check your work in a different way, trace the value of message after each line. It starts as Coding is , becomes Coding is worthwhile after the first +=, and then Coding is worthwhile, isn't it? after the second. Nothing is printed until the last line.
Common mistakes
- Writing
=instead of+=.message = adjective;replaces the text instead of extending it. - Printing too early. The print must come after both appends, or the output is incomplete.
- Quoting a variable name.
message += "adjective";appends the word "adjective", not the variable's value. - Typos in the literal. The tests compare the text exactly, so the comma, space and question mark must match.
Because the message is built in the same variable, the order of the appends decides the order of the words. Swap the two += lines and the sentence comes out scrambled.
Key takeaways
+joins strings and+=joins and assigns in one step.- Strings never change in place: each join makes a new string.
- Add spaces and punctuation yourself.
- Print after you have finished building the message.