Introduction to string concatenation

A beginner guide to programming with .NET 5 and C#

Posted by Carl-Hugo Marcotte on March 21, 2021
Introduction to string concatenation
Photo by Jefferson Santos on Unsplash

In this article, we dig a little more into the string type. We also explore how to concatenate (combine) strings. As a programmer, you will often need to manipulate strings, concatenation and interpolation being two recurring themes. We will cover interpolation in the next installment.

This article is part of a learn programming series where you need no prior knowledge of programming. If you want to learn how to program and want to learn it using .NET/C#, this is the right place. I suggest reading the whole series in order, starting with Creating your first .NET/C# program, but that’s not mandatory.

This article is the first part of a sub-series showcasing the following articles:

Strings

In C#, a string is a sequence of characters delimited by quotes ("). We used strings in previous articles to write text to the console.

As a reminder, here is how to create a string variable:

var name = "Superman";

We already used strings, so no need to linger too long here. Next, we explore some new content: multiline strings.

Multiline strings

In C#, we can create multiline strings by prefixing the string with the @ character. As the name implies, the only difference is the possibility to set the content of the string over multiple lines.

Here is an example of a multiline string:

var name = @"This
is
a
multiline
string!";
// More code here...

But keep an eye open for details. For example, in the following code, the first and last characters are a new line, which may not be what you expected to write.

var name = @"
This
is
a
multiline
string!
";
// More code here...

Multiline strings are handy in different scenarios where you don’t want to use concatenation. As an introduction to strings, I will not get into too many more details. However, there are many methods to manipulate strings, compare them, or optimize their usage.

Next, we look into the main subject: concatenation.

Concatenation

Concatenation is the action of piecing multiple strings together to make a new one; combining strings if you wish. In C#, the concatenation operator is the + symbol. The + operator combines both string operands (the values on the left and right sides) into a new string. Let’s look into an example to make learning easier:

var concatenatedString = "Greetings " + "from .NET!";
Console.WriteLine(concatenatedString);

The preceding code combines the strings "Greetings " and "from .NET!" into "Greetings from .NET!".

Note the space after the word Greetings. Without it, the combined string would have been "Greetingsfrom .NET!".

Another way to do it, which is more likely to happen than what we just did, is assigning a value to a variable and then updating that value. Here is an example of that:

var concatenatedString = "Greetings ";
concatenatedString = concatenatedString + "from .NET!";
Console.WriteLine(concatenatedString);

The preceding code does the same as "Greetings " + "from .NET!", but in two steps (bullets 1 and 2):

  1. The value "Greetings " is assigned to the concatenatedString variable.
  2. The value "from .NET!" is added at the end of the concatenatedString variable, then reassigned to it.
  3. The program writes "Greetings from .NET!" to the console.

Let’s look more into the line concatenatedString = concatenatedString + "from .NET!"; as it may be harder to understand at first.

Reminder: the assignation operator (=) has the lowest priority, so the code on the right (the right-hand operand) is processed first.

Here is an image to help analyze the code:

Code execution order

  1. The program ready the literal string "Greetings " for step 2.
  2. The program assigns the value of the right-hand operand ("Greetings ") to the concatenatedString variable.
  3. The program ready the current value of the concatenatedString variable for step 5 ("Greetings ").
  4. The program ready the literal string "from .NET!" for step 5.
  5. The program concatenates (combines) the two strings into a new one.
  6. The program assigns the value of the right-hand operand ("Greetings from .NET!") to the concatenatedString variable, replacing its value.

Note: You can see steps 3 to 5 as evaluated first, like one big step, then the program continues at step 6.

Now that we covered that, there is a shortcut to this process: the += operator. You can see the += operator as a combination of both concatenation (+) and assignation (=). The previous example, using the += operator, would look like this:

var concatenatedString = "Greetings ";
concatenatedString += "from .NET!";
Console.WriteLine(concatenatedString);

The second line of code is simplified compared to the previous bloc. It does the same, without the need to specify that concatenatedString = concatenatedString + [something else]. This new syntax removes unneeded pieces, reducing the length of the line of code, most likely even making it easier to read.

Enough theory; next, it’s your turn to try it out.

Exercise

To practice concatenation, we will update the code from the previous article’s exercise, but with a twist. You must ask for the user’s first and last name again, and then you must use concatenation to output the result using a single Console.WriteLine call.

Here is the previous solution, including the Title and Clear additions:

using System;

Console.Title = "IntroToDotNet";

Console.Write("What is your first name? ");
var firstName = Console.ReadLine();
Console.Clear();

Console.Write("What is your last name? ");
var lastName = Console.ReadLine();
Console.Clear();

// TODO: rewrite the following code
Console.Write("Greetings ");
Console.Write(firstName);
Console.Write(" ");
Console.Write(lastName);
Console.WriteLine("!");

Here are a few optional hints in case you feel stuck:

Hint 1

You can create a variable to hold that concatenated string before writing it to the console.

Hint 2

You can concatenate multiple values back to back, like this:

var greetings = "Greetings " + "Carl-Hugo" + " " + "Marcotte" + "!";

Once you are done, you can compare with My Solution below.

My Solution

Program.cs

using System;

Console.Title = "IntroToDotNet";

Console.Write("What is your first name? ");
var firstName = Console.ReadLine();
Console.Clear();

Console.Write("What is your last name? ");
var lastName = Console.ReadLine();
Console.Clear();

// Only the following code changed
var greetings = "Greetings " + firstName + " " + lastName + "!";
Console.WriteLine(greetings);

An alternative style would have been the following:

var greetings = "Greetings ";
greetings += firstName;
greetings += " ";
greetings += lastName;
greetings += "!";
Console.WriteLine(greetings);

Both styles would have yielded the same results, and both are acceptable.

But which one to pick? Pick the style that you prefer or the more suitable style for the program you are building. You don’t always have all the values firsthand, making the second style more suitable for those scenarios.

Don’t worry if your solution is different than mine. As long as you completed it, it means you understood the lesson or at least practiced. Practicing is the key to success!

Good job! You completed another small chapter of your programming journey.

Conclusion

In this article, we learned that we could write multiline strings if we need to. We also learned about concatenation, which combines multiple strings into a new one. The concatenation operator is the symbol +. We also look at the += operator. += allows us to combine both the concatenation and assignation operators. Using it can simplify our code and remove a step. In programs, concatenation is often used, which makes it an essential piece of knowledge to have.

Next step

It is now time to move to the next article: Introduction to string interpolation.

Table of content

Now that you are done with this article, please look at the series’ content.

Articles in this series
Creating your first .NET/C# program
In this article, we are creating a small console application using the .NET CLI to get started with .NET 5+ and C#.
Introduction to C# variables
In this article, we explore variables. What they are, how to create them, and how to use them. Variables are essential elements of a program, making it dynamic.
Introduction to C# constants
In this article, we explore constants. A constant is a special kind of variable.
Introduction to C# comments
In this article, we explore single-line and multiline comments.
How to read user inputs from a console
In this article, we explore how to retrieve simple user inputs from the console. This will help us make our programs more dynamic by interacting with the user.
Introduction to string concatenation You are here
In this article, we dig deeper into strings and explore string concatenation.
Introduction to string interpolation
In this article, we explore string interpolation as another way to compose a string.
Escaping characters in C# strings
In this article, we explore how to escape characters like quotes and how to write special character like tabs and new lines.
Introduction to Boolean algebra and logical operators
This article introduces the mathematical branch of algebra that evaluates the value of a condition to true or false.
Using if-else selection statements to write conditional code blocks
In this article, we explore how to write conditional code using Boolean algebra.
Using the switch selection statement to simplify conditional statements blocks
In this article, we explore how to simplify certain conditional blocks by introducing the switch statement.
Boolean algebra laws
This article explores multiple Boolean algebra laws in a programmer-oriented way, leaving the mathematic notation aside.
This is the end of this series
This article series was migrated to a newest version of .NET. Have a look at the .NET 6 series for more!




Comments