Ask Learn Preview
Please sign in to use this experience.
Sign inThis browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Often, you'll need to combine data from many different sources, including literal strings and variables containing both text and numeric data. In this unit, you'll use string concatenation to combine two or more values into a new string.
String concatenation is "programmer speak" for simply combining two or more string
values into a new string
value. Unlike addition, the second value is appended to the end of the first value, and so on. In the following exercise, you'll write code to concatenate string
values together.
To concatenate two strings together, you use the string concatenation operator, which is the plus symbol +
.
Select all of the code in the .NET Editor, and press Delete or Backspace to delete it.
Enter the following code in the code editor:
string firstName = "Bob";
string message = "Hello " + firstName;
Console.WriteLine(message);
Now, run the code. You'll see the following result in the output console:
Hello Bob
Notice the order—the first string "Hello "
is first in the new string, and the value in the firstName
variable is appended to the end of it.
You can perform several concatenation operations in the same line of code.
Modify the code you wrote earlier to the following:
string firstName = "Bob";
string greeting = "Hello";
string message = greeting + " " + firstName + "!";
Console.WriteLine(message);
Here you create a more complex message by combining several variables and literal strings.
Now, run the code. You'll see the following result in the output console:
Hello Bob!
In the previous steps, you used an extra variable to hold the new string that resulted from the concatenation operation. Unless you have a good reason to do so, you can (and should) avoid using intermediate variables by performing the concatenation operation as you need it.
Modify the code you wrote earlier to the following:
string firstName = "Bob";
string greeting = "Hello";
Console.WriteLine(greeting + " " + firstName + "!");
Now, run the code. The result in the output console should be the same even if you simplified the code:
Hello Bob!
Here's what you've learned about string concatenation so far:
Please sign in to use this experience.
Sign in