C# String Concatenation: Combine Text with the + Operator
Exercise – Combine Strings Using String Concatenation
In many applications, you'll often combine data from different sources—literal text, variables, and even numeric values. In this unit, you'll learn how C# uses string concatenation to merge multiple pieces of text into one meaningful string.
What is string concatenation?
String concatenation simply means combining two or more string values into a single string. Unlike numeric addition, concatenation appends one value to another in sequence. In this exercise, you’ll write C# code to join string values together.Concatenate a literal string and a variable
To concatenate text, use the+ operator. Replace any previous code in your editor, then enter:string firstName = "Bob"; string message = "Hello " + firstName; Console.WriteLine(message);
Output:
Hello BobThe literal string
"Hello " appears first, and the value stored in firstName is appended immediately after it.Concatenate multiple variables and literal strings
You can concatenate several components in a single line:string firstName = "Bob"; string greeting = "Hello"; string message = greeting + " " + firstName + "!"; Console.WriteLine(message);
Output:
Hello Bob!This example builds a complete message by combining multiple values seamlessly.
Avoiding intermediate variables
You don't always need an extra variable to hold the final string. If it doesn't increase clarity, you can concatenate directly insideConsole.WriteLine:string firstName = "Bob"; string greeting = "Hello"; Console.WriteLine(greeting + " " + firstName + "!");
Output:
Hello Bob!The result stays the same, but the code becomes cleaner by removing unnecessary variables.
Recap
• String concatenation lets you combine smaller text pieces into a single string.• Avoid extra variables unless they make your code easier to understand.
Continue learning
- Module 4 lesson guide
- C# Escape Sequences, Verbatim Strings and Unicode
- C# String Interpolation: Combine Text and Variables
Further reading: Microsoft documentation.
Concatenation and arithmetic: common mistakes
Why does "Total: " + 2 + 3 display Total: 23?
The + operators are evaluated from left to right. After the first operation produces a string, the next number is appended as text. Use "Total: " + (2 + 3) when you want addition before concatenation.
Practice and check
Predict the result of 2 + 3 + " total" before running it. It should be 5 total. Compare all three expressions and explain which operation happens first.
Comments
Post a Comment