C# String Concatenation
Concatenation means joining two or more strings together to build a larger piece of text. It is one of the first things you will do when combining fixed words with values from your program.
Joining with the + Operator
The simplest way to concatenate strings is with the + operator. C# glues the strings together in the exact order you write them, with no spaces added automatically, so you include any spaces yourself.
Combining two strings
string firstName = "Ada";
string lastName = "Lovelace";
string fullName = firstName + " " + lastName;
Console.WriteLine(fullName); // Ada LovelaceWatch Out: + Also Adds Numbers
The + operator does two jobs. Between numbers it performs addition, and between strings it performs concatenation. When you mix a number and a string, C# treats the whole expression as text and joins them, which can lead to surprising results.
Number vs text
int x = 10;
int y = 5;
Console.WriteLine(x + y); // 15 (math)
Console.WriteLine("Total: " + x + y); // Total: 105 (text!)- "Total: " + x turns x into text, giving "Total: 10".
- That result + y appends y as text, giving "Total: 105".
- Wrap the math in parentheses to fix it: "Total: " + (x + y) gives "Total: 15".
Using string.Concat()
You can also join strings with the built-in string.Concat() method. It accepts several strings and returns them combined into one. This is functionally similar to using +, and it reads clearly when you have a fixed set of parts.
Concat method
string part1 = "Learning ";
string part2 = "C# ";
string part3 = "is fun";
string sentence = string.Concat(part1, part2, part3);
Console.WriteLine(sentence); // Learning C# is fun