0
0
CsharpHow-ToBeginner · 3 min read

How to Concatenate Strings in C# - Simple Guide

In C#, you can concatenate strings using the + operator, the string.Concat() method, or string interpolation with $"...". These methods join multiple strings into one easily and clearly.
📐

Syntax

Here are common ways to concatenate strings in C#:

  • string1 + string2: Uses the plus operator to join strings.
  • string.Concat(string1, string2): Calls a method to join strings.
  • $"{string1} {string2}": Uses string interpolation to combine strings with variables.
csharp
string result1 = "Hello" + " " + "World!";
string result2 = string.Concat("Hello", " ", "World!");
string name = "World";
string result3 = $"Hello {name}!";
💻

Example

This example shows how to join strings using the plus operator, string.Concat, and string interpolation. It prints the combined results.

csharp
using System;

class Program
{
    static void Main()
    {
        string part1 = "Good";
        string part2 = "Morning";

        // Using + operator
        string greeting1 = part1 + " " + part2 + "!";

        // Using string.Concat method
        string greeting2 = string.Concat(part1, " ", part2, "!");

        // Using string interpolation
        string greeting3 = $"{part1} {part2}!";

        Console.WriteLine(greeting1);
        Console.WriteLine(greeting2);
        Console.WriteLine(greeting3);
    }
}
Output
Good Morning! Good Morning! Good Morning!
⚠️

Common Pitfalls

Some common mistakes when concatenating strings in C# include:

  • Forgetting spaces between words when using + operator, resulting in joined words without spaces.
  • Using string.Concat without separators, which also joins strings directly.
  • Trying to concatenate null values without checking, which can cause unexpected results.

Always add spaces explicitly if needed and handle null values carefully.

csharp
string a = "Hello";
string b = "World";

// Wrong: missing space
string wrong = a + b; // Output: HelloWorld

// Right: add space
string right = a + " " + b; // Output: Hello World
📊

Quick Reference

Here is a quick summary of string concatenation methods in C#:

MethodDescriptionExample
+ operatorJoins strings directly"Hello" + " " + "World"
string.Concat()Concatenates multiple stringsstring.Concat("Hello", " ", "World")
String InterpolationEmbeds variables in strings$"Hello {name}"

Key Takeaways

Use the + operator or string.Concat() to join strings simply.
String interpolation ($"...") is a clean way to combine strings and variables.
Always add spaces explicitly when concatenating words.
Check for null values to avoid unexpected results.
Choose the method that makes your code clear and readable.