Concatenate Strings in C#

Different ways to concatenate strings in c# | Top 6 Ways to Concatenate String

Hello folks, in this post we will try to understand different ways to concatenate strings in C#. As all we know Strings in C# are immutable because a string cannot be changed once created. If we will perform any other operation it will create new string object.

The term “concatenate”, we will use to merge or join two or more string objects or literals. Let’s try to understand different ways of concatenate string objects. There are basic 6 ways to concatenate string in C# as below:

1. Using the + and the += Operators

If we will use + operator to concatenate string objects, it will translate to String.Concat() in the IL.

Let understand concatenating strings using +

string firstName = "Dhruv";
string lastName = "Sheth";
string fullName = firstName + " " + lastName;
            
Console.WriteLine("1. Using the + and the += Operators");
Console.WriteLine("Using the +  operator");
Console.WriteLine(fullName); // Output: "Dhruv Sheth"

Let understand concatenating strings using +=

string[] data = {firstName," ",lastName };
string fullNamePlusEqual = string.Empty;
foreach (var item in data)
        fullNamePlusEqual +=item;
              
Console.WriteLine("Using the += operator");
Console.WriteLine(fullName); // Output: "Dhruv Sheth"

2. String.Format() Method

The String.Format() method is used to join and format our string in various ways. It has eight overloaded and very versatile.
The most commonly used : static String Format(String format, params object?[] args);

string firstNameFormat = "Dhruv";
string lastNameFormat = "Sheth";
string fullNameFormat  = string.Format("{0} {1}", firstNameFormat, lastNameFormat);
            
Console.WriteLine("2. String.Format() Method");
Console.WriteLine(fullName); // Output: "Dhruv Sheth"

As you can see that firstNameFormat and lastNameFormat represent {0} and {1} respectively. Please note, if there will be more inputs than provided arguments, we will get FormatException from the compiler.

string fullNameInvalidFormat = string.Format("{0} {1} {2}", firstNameFormat, lastNameFormat);

There are 3 places to insert strings and only 2 arguments are provided which would cause FormatException.

3. Using String Interpolation(C# 6 Feature)

String Interpolation is the newest way of joining multiple strings. It’s very intuitive & easy way. By using string interpolation, we are bypassing String.Format(). We need to use $ in the starting and use variable covered by {YOUR_VARIABLE} as shown in below example:

Starting with C# 8.0, you can use the $ and @ tokens in any order: both $@”…” and @$”…” are valid interpolated verbatim strings. However, the $ token must appear before the @ token in older C# versions.

private static void StringInterpolation()
{
    string firstName = "Dhruv";
    string lastName = "Sheth";
    DateTime date = DateTime.Now;

    Console.WriteLine("3. Using String Interpolation(C# 6 Feature)");
    Console.WriteLine($" Hi, {firstName} {lastName}, it's {date:HH:mm} now."); // Output: "Hi, Dhruv Sheth, it's 17:02 now."
}

4. Joining Strings with String.Join() Method

String.Join() specially used in concatenating elements of collection or arrays.

If we have list or array and we need to join them, by using some kind of separator like comma (,) or space or anything else whatever you would require, we would use the String.Join() method.

Let’s try to understand by using example:

private static void StringJoin()
{
    string[] data = { "Dhruv", "Sheth" };
    string FullName = string.Join(" ", data);
    Console.WriteLine("4. Joining Strings with String.Join() Method");
    Console.WriteLine(FullName); // Output:Dhruv Sheth
}

Second example is to join integer of array using comma using as shown below:

int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
string foobar = String.Join(",", array); 

Console.WriteLine(foobar); // outputs "1,2,3,4,5,6,7,8,9"

5. StringBuilder.Append() Method

To overcome the problem of immutable, StringBuilder class will be used.

Whenever you will use string object or join/concatenating multiple string objects, it will allocate much more memory because in every operation strings require a new memory will be allocated. Therefore to avoid this kind of memory allocation issue we can use StringBuilder class which doesn’t create new strings when modification will take place.

Let’s understand concept by using example shown as below:

private static void StringBuilderAppend()
{
    string firstName = "Dhruv";
    string lastName = "Sheth";
    StringBuilder stringBuilder = new StringBuilder();

    stringBuilder.Append(firstName);
    stringBuilder.Append(" ");
    stringBuilder.Append(lastName);

    Console.WriteLine("5. StringBuilder.Append() Method");
    Console.WriteLine(stringBuilder); // output: Dhruv Sheth
}

6. String.Concat() Method

String.Concat() method is very powerful and versatile for concatenate strings. This method contains 11 different overloaded methods. Though, we will use basic overloaded method only.

We can concatenate two or more strings. Let’s understand how can we use this method by using below example:

private static void String_Concate()
{
    string firstName = "Dhruv";
    string lastName = "Sheth";

    string fullName = string.Concat(firstName, " ", lastName);

    Console.WriteLine("6. String.Concat() Method");
    Console.WriteLine(fullName); // output:Dhruv Sheth
}

Full Source code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace String_Concate
{
    class Program
    {
        static void Main(string[] args)
        {
            //1. Using the + and the += Operators
            PlusOperator();

            //2. String.Format() Method
            StringFormat();

            //3. Using String Interpolation(C# 6 Feature)
            StringInterpolation();

            //4. Joining Strings with String.Join() Method
            StringJoin();

            //5. StringBuilder.Append() Method
            StringBuilderAppend();

            //6. String.Concat() Method
            String_Concate();

            Console.ReadKey();
        } 

        private static void PlusOperator()
        {
            //Let understand concating strings using + 
            string firstName = "Dhruv";
            string lastName = "Sheth";
            string fullName = firstName + " " + lastName;

            Console.WriteLine("1. Using the + and the += Operators");
            Console.WriteLine(" Using the +  operator");
            Console.WriteLine(fullName); // Output: "Dhruv Sheth"

            //Let understand concating strings using +=

            string[] data = { firstName, " ", lastName };
            string fullNamePlusEqual = string.Empty;
            foreach (var item in data)
                fullNamePlusEqual += item;


            Console.WriteLine(" Using the += operator");
            Console.WriteLine(fullName); // Output: "Dhruv Sheth"

        }

        private static void StringFormat()
        {
            string firstNameFormat = "Dhruv";
            string lastNameFormat = "Sheth";
            string fullNameFormat = string.Format(" {0} {1}", firstNameFormat, lastNameFormat);

            Console.WriteLine("2. String.Format() Method");
            Console.WriteLine(fullNameFormat); // Output: "Dhruv Sheth"
        }


        private static void StringInterpolation()
        {
            string firstName = "Dhruv";
            string lastName = "Sheth";
            DateTime date = DateTime.Now;

            Console.WriteLine("3. Using String Interpolation(C# 6 Feature)");
            Console.WriteLine($" Hi, {firstName} {lastName}, it's {date:HH:mm} now."); // Output: "Hi, Dhruv Sheth, it's 17:02 now."
        }
        private static void StringJoin()
        {
            string[] data = { "Dhruv", "Sheth" };
            string FullName = string.Join(" ", data);
            Console.WriteLine("4. Joining Strings with String.Join() Method");
            Console.WriteLine(FullName);

            int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            string foobar = String.Join(",", array);

            Console.WriteLine(foobar); // outputs "1,2,3,4,5,6,7,8,9"
        }

        private static void StringBuilderAppend()
        {
            string firstName = "Dhruv";
            string lastName = "Sheth";
            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.Append(firstName);
            stringBuilder.Append(" ");
            stringBuilder.Append(lastName);

            Console.WriteLine("5. StringBuilder.Append() Method");
            Console.WriteLine(stringBuilder); // output: Dhruv Sheth
        }

        private static void String_Concate()
        {
            string firstName = "Dhruv";
            string lastName = "Sheth";

            string fullName = string.Concat(firstName, " ", lastName);

            Console.WriteLine("6. String.Concat() Method");
            Console.WriteLine(fullName); // output:Dhruv Sheth
        }
    }
}

Which one should I use?

Guys to understand which should we use over others, we need to consider condition where we are going to implement and other thing is performance. For performance comparison I would suggest to visit https://dotnetcoretutorials.com/2020/02/06/performance-of-string-concatenation-in-c/

I want to add that if you are planning to append string multiple times in your code, you must use StringBuilder for concatenating string in C#

Conclusion

In this short tutorial, we have understood different ways to concatenate strings in C#. Now kindly play around with different ways to concatenate strings in C# and implement them.

Happy Coding!!

Leave a Reply